How do I check if a file exists in Java?

后端 未结 17 2416
盖世英雄少女心
盖世英雄少女心 2020-11-22 00:50

How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl\'s -e $filename

17条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 01:24

    There are multiple ways to achieve this.

    1. In case of just for existence. It could be file or a directory.

      new File("/path/to/file").exists();
      
    2. Check for file

      File f = new File("/path/to/file"); 
        if(f.exists() && f.isFile()) {}
      
    3. Check for Directory.

      File f = new File("/path/to/file"); 
        if(f.exists() && f.isDirectory()) {}
      
    4. Java 7 way.

      Path path = Paths.get("/path/to/file");
      Files.exists(path)  // Existence 
      Files.isDirectory(path)  // is Directory
      Files.isRegularFile(path)  // Regular file 
      Files.isSymbolicLink(path)  // Symbolic Link
      

提交回复
热议问题