Check if a path represents a file or a folder

前端 未结 8 427
伪装坚强ぢ
伪装坚强ぢ 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 21:56
    String path = "Your_Path";
    File f = new File(path);
    
    if (f.isDirectory()){
    
    
    
      }else if(f.isFile()){
    
    
    
      }
    
    0 讨论(0)
  • 2020-12-07 21:59

    To check if a string represents a path or a file programatically, you should use API methods such as isFile(), isDirectory().

    How does system understand whether there's a file or a folder?

    I guess, the file and folder entries are kept in a data structure and it's managed by the file system.

    0 讨论(0)
  • 2020-12-07 22:05
    public static boolean isDirectory(String path) {
        return path !=null && new File(path).isDirectory();
    }
    

    To answer the question directly.

    0 讨论(0)
  • 2020-12-07 22:06

    Clean solution while staying with the nio API:

    Files.isDirectory(path)
    Files.isRegularFile(path)
    
    0 讨论(0)
  • 2020-12-07 22:06
       private static boolean isValidFolderPath(String path) {
        File file = new File(path);
        if (!file.exists()) {
          return file.mkdirs();
        }
        return true;
      }
    
    0 讨论(0)
  • 2020-12-07 22:11

    Please stick to the nio API to perform these checks

    import java.nio.file.*;
    
    static Boolean isDir(Path path) {
      if (path == null || !Files.exists(path)) return false;
      else return Files.isDirectory(path);
    }
    
    0 讨论(0)
提交回复
热议问题