如果我这样做:
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()是正确的方法.不要试图优化它.
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).当您测试文件存在时,可能会有三个结果:
- 该文件已验证存在.
- 该文件已验证不存在.
- 文件的状态未知.当程序无权访问该文件时,可能会发生此结果.
如果同时
exists和notExists回报false,该文件的存在,无法验证.