在Java中(相当于Perl的-e $filename)打开文件读取之前,如何检查文件是否存在?
SO中唯一类似的问题涉及写入文件,因此使用FileWriter来回答,这显然不适用于这里。
如果可能的话,我更喜欢一个真正的API调用返回true/false,而不是一些“调用API打开一个文件,并在它抛出一个异常时捕获你检查文本中的‘无文件’”,但我可以接受后者。
在Java中(相当于Perl的-e $filename)打开文件读取之前,如何检查文件是否存在?
SO中唯一类似的问题涉及写入文件,因此使用FileWriter来回答,这显然不适用于这里。
如果可能的话,我更喜欢一个真正的API调用返回true/false,而不是一些“调用API打开一个文件,并在它抛出一个异常时捕获你检查文本中的‘无文件’”,但我可以接受后者。
当前回答
有多种方法可以实现这一点。
In case of just for existence. It could be file or a directory. new File("/path/to/file").exists(); Check for file File f = new File("/path/to/file"); if(f.exists() && f.isFile()) {} Check for Directory. File f = new File("/path/to/file"); if(f.exists() && f.isDirectory()) {} 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
其他回答
熟悉Commons FileUtils https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html也是非常值得的 它有额外的管理文件的方法,通常比JDK更好。
你可以使用以下方法:
具有良好编码实践并涵盖所有情况的简单示例:
private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
if (f.exists()) {
throw new FileAlreadyExistsException(f.getAbsolutePath());
} else {
try {
URL u = new URL(url);
FileUtils.copyURLToFile(u, f);
} catch (MalformedURLException ex) {
Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
参考和更多的例子在
https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations
f.isFile() && f.canRead()
不喜欢。只是捕捉FileNotFoundException。文件系统必须测试文件是否存在。把所有的事情都做两次是没有意义的,原因如下:
双倍代码 计时窗口问题,即文件可能在测试时存在,但在打开时不存在,反之亦然 事实上,这个问题的存在表明,你可能做了错误的测试,得到了错误的答案。
不要试图猜测这个系统。它知道。不要试图预测未来。一般来说,测试任何资源是否可用的最佳方法就是尝试使用它。