问题
在打开文件以便在Java中读取之前,如何检查文件是否存在? (相当于Perl的-e $ filename
)。
编写文件的唯一similar question on SO,因此使用FileWriter回答,这显然不适用于此处。
如果可能的话,我更喜欢真正的API调用返回true / false,而不是某些“调用API来打开文件并在它抛出异常时捕获,你在文本中检查'无文件'”,但我可以忍受后者。
#1 热门回答(1136 赞)
使用java.io.File
:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
#2 热门回答(374 赞)
我建议使用isFile()
而不是exists()
。大多数情况下,你要检查路径是否指向文件,而不仅仅是它存在。请记住,如果你的路径指向目录,exists()
将返回true。
new File("path/to/file.txt").isFile();
new File(“C:/”)。exists()
将返回true但不允许你打开并从中读取文件。
#3 热门回答(118 赞)
通过在Java SE 7中使用nio,
import java.nio.file.*;
Path path = Paths.get(filePathString);
if (Files.exists(path)) {
// file exist
}
if (Files.notExists(path)) {
// file is not exist
}
如果两者都存在且notExists返回false,则无法验证文件是否存在。 (也许没有访问权限)
你可以检查路径是目录还是常规文件。
if (Files.isDirectory(path)) {
// path is directory
}
if (Files.isRegularFile(path)) {
// path is regular file
}