Một cách khác để kiểm tra đường dẫn có phải là thư mục hay không? (How to checking path is File or Directory by BasicFileAttributes?)






Việc xác định một tập tin hay đường dẫ(path) là Folder hay File, được thực hiện rất dễ dàng bằng "new File(path).isDirectory();" đây là phương pháp thông dụng nhất. Trong bài viết này tôi chỉ giới thiệu thêm một cách khác để kiểm tra vấn đề này bằng cách dùng  BasicFileAttributes.






Giả sử tôi có một đường dẫn thư mục(path folder) sau:

D:\Z-Test\VNLIVES_NET\

Và giờ tôi phải viết một chương trình Java để kiểm tra đường dẫn trên là tập tin hay thư mục(folder or file)?

/**
 * @(#)JavaCheckPathIsFolder.java
 *
 * JavaCheckPathIsFolder application
 *
 * @author developer.bnson@gmail.com
 * @version 1.00 2014/3/15
 */

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.Files;

public class JavaCheckPathIsFolder {
   
    public static void main(String[] args) {

        File file =new File("D:\\Z-Test\\VNLIVES_NET\\");
       
        try {
           
            BasicFileAttributes bfa = Files.readAttributes(file.toPath(), BasicFileAttributes.class);   
            System.out.println("Path is folder: " + bfa.isDirectory());
           
               
        } catch (Exception ex) {
           
        }  
           

    }
}

Sau khi chạy chương trình kết quả sẽ là.

Path is folder: true


















No comments:

Post a Comment