检查文件是否存在而不创建它

如果我这样做:

File f = new File("c:\\text.txt"); if (f.exists()) { System.out.println("File exists"); } else { System.out.println("File not found!"); } 

然后创建文件并始终返回“文件存在”。 是否可以在不创建文件的情况下检查文件是否存在?

编辑:

我忘了提到它是在for循环中。 所以这是真实的事情:

 for (int i = 0; i < 10; i++) { File file = new File("c:\\text" + i + ".txt"); System.out.println("New file created: " + file.getPath()); } 

当您实例化File ,您不是在磁盘上创建任何东西,而只是构建一个可以调用某些方法的对象,例如exists()

这很好又便宜,不要试图避免这种情况。

File实例只有两个字段:

 private String path; private transient int prefixLength; 

这是构造函数:

 public File(String pathname) { if (pathname == null) { throw new NullPointerException(); } this.path = fs.normalize(pathname); this.prefixLength = fs.prefixLength(this.path); } 

如您所见, File实例只是路径的封装。 创建它以调用exists()是正确的继续方法。 不要试图优化它。

创建File实例不会在文件系统上创建文件,因此发布的代码将执行您所需的操作。

Java 7开始,您可以使用java.nio.file.Files.exists

 Path p = Paths.get("C:\\Users\\first.last"); boolean exists = Files.exists(p); boolean notExists = Files.notExists(p); if (exists) { System.out.println("File exists!"); } else if (notExists) { System.out.println("File doesn't exist!"); } else { System.out.println("File's status is unknown!"); } 

在Oracle教程中,您可以找到有关此内容的一些详细信息:

Path类中的方法是语法,这意味着它们在Path实例上运行。 但最终您必须访问文件系统以validation特定Path存在或不存在。 您可以使用exists(Path, LinkOption...)notExists(Path, LinkOption...)方法执行此操作。 请注意!Files.exists(path)不等同于Files.notExists(path) 。 当您测试文件存在时,可能会有三个结果:

  • 该文件已validation存在。
  • 该文件已validation不存在。
  • 文件的状态未知。 当程序无权访问该文件时,可能会发生此结果。

如果两者都existsnotExists返回false ,则无法validation文件是否存在。

Files.exists方法在JDK 8中的性能明显较差,并且在用于检查实际不存在的文件时会显着减慢应用程序的速度。

这也可以应用于Files.noExists,Files.isDirectory和Files.isRegularFile

根据这个你可以使用以下内容:

 Paths.get("file_path").toFile().exists()