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

Thr*_*eaT 24 java file-io

如果我这样做:

File f = new File("c:\\text.txt");

if (f.exists()) {
    System.out.println("File exists");
} else {
    System.out.println("File not found!");
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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

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

Den*_*ret 52

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

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

File实例只有两个字段:

private String path;
private transient int prefixLength;
Run Code Online (Sandbox Code Playgroud)

这是构造函数:

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

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

  • @ThreaT:与普遍看法相反,在循环中运行代码不会**从根本上改变代码的作用. (5认同)
  • @ThreaT:那个代码**仍然**不会在你的硬盘上创建文件,*除非你正在谈论*它不是*`java.io.File`.您的项目中是否有任何其他可能(意外)使用的名为`File`的类? (2认同)

hmj*_*mjd 10

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


ROM*_*eer 10

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!");
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

如果同时existsnotExists回报false,该文件的存在,无法验证.