Check if a path represents a file or a folder

前端 未结 8 442
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 21:41

I need a valid method to check if a String represents a path for file or a directory. What are valid directory names in Android? As it comes out, folder names c

相关标签:
8条回答
  • 2020-12-07 22:17

    Assuming path is your String.

    File file = new File(path);
    
    boolean exists =      file.exists();      // Check if the file exists
    boolean isDirectory = file.isDirectory(); // Check if it's a directory
    boolean isFile =      file.isFile();      // Check if it's a regular file
    

    See File Javadoc


    Or you can use the NIO class Files and check things like this:

    Path file = new File(path).toPath();
    
    boolean exists =      Files.exists(file);        // Check if the file exists
    boolean isDirectory = Files.isDirectory(file);   // Check if it's a directory
    boolean isFile =      Files.isRegularFile(file); // Check if it's a regular file
    
    0 讨论(0)
  • 2020-12-07 22:18

    There is no way for the system to tell you if a String represent a file or directory, if it does not exist in the file system. For example:

    Path path = Paths.get("/some/path/to/dir");
    System.out.println(Files.isDirectory(path)); // return false
    System.out.println(Files.isRegularFile(path)); // return false
    

    And for the following example:

    Path path = Paths.get("/some/path/to/dir/file.txt");
    System.out.println(Files.isDirectory(path));  //return false
    System.out.println(Files.isRegularFile(path));  // return false
    

    So we see that in both case system return false. This is true for both java.io.File and java.nio.file.Path

    0 讨论(0)
提交回复
热议问题