26

如果我这样做:

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());
}
4

4 回答 4

54

当您实例化 aFile时,您不会在磁盘上创建任何东西,而只是构建一个可以调用某些方法的对象,例如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()是正确的方法。不要试图优化它。

于 2012-07-02T10:24:14.050 回答
12

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实例进行操作。但最终您必须访问文件系统以验证特定的Path存在或不存在。exists(Path, LinkOption...)您可以使用和方法来做到这一点notExists(Path, LinkOption...)。请注意,!Files.exists(path)不等价于Files.notExists(path). 当您测试文件的存在时,可能会出现三种结果:

  • 该文件已验证存在。
  • 该文件经验证不存在。
  • 文件状态未知。当程序无权访问该文件时,可能会出现此结果。

如果两者都exists返回notExistsfalse则无法验证文件的存在。

于 2016-06-02T12:24:01.630 回答
11

创建File实例不会在文件系统上创建文件,因此发布的代码将满足您的要求。

于 2012-07-02T10:23:56.050 回答
3

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

这也适用于 Files.noExists、Files.isDirectory 和 Files.isRegularFile

据此,您可以使用以下内容:

Paths.get("file_path").toFile().exists()
于 2018-03-27T13:42:59.623 回答