在Java中(相当于Perl的-e $filename)打开文件读取之前,如何检查文件是否存在?
SO中唯一类似的问题涉及写入文件,因此使用FileWriter来回答,这显然不适用于这里。
如果可能的话,我更喜欢一个真正的API调用返回true/false,而不是一些“调用API打开一个文件,并在它抛出一个异常时捕获你检查文本中的‘无文件’”,但我可以接受后者。
在Java中(相当于Perl的-e $filename)打开文件读取之前,如何检查文件是否存在?
SO中唯一类似的问题涉及写入文件,因此使用FileWriter来回答,这显然不适用于这里。
如果可能的话,我更喜欢一个真正的API调用返回true/false,而不是一些“调用API打开一个文件,并在它抛出一个异常时捕获你检查文本中的‘无文件’”,但我可以接受后者。
当前回答
你可以使用以下方法:
其他回答
具有良好编码实践并涵盖所有情况的简单示例:
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
设计这些方法是有特定目的的。我们不能说使用任何人来检查文件是否存在。
isFile():测试由这个抽象路径名表示的文件是否是一个正常的文件。 exists():测试由此抽象路径名表示的文件或目录是否存在。 docs.oracle.com
我建议使用isFile()而不是exists()。大多数情况下,您需要检查路径是否指向一个文件,而不仅仅是它是否存在。记住,如果您的路径指向一个目录,exists()将返回true。
new File("path/to/file.txt").isFile();
new File("C:/").exists()将返回true,但不允许您将其作为文件打开并从中读取。
You must use the file class , create a file instance with the path of the file you want to check if existent . After that you must make sure that it is a file and not a directory . Afterwards you can call exist method on that file object referancing your file . Be aware that , file class in java is not representing a file . It actually represents a directory path or a file path , and the abstract path it represents does not have to exist physically on your computer . It is just a representation , that`s why , you can enter a path of a file as an argument while creating file object , and then check if that folder in that path does really exist , with the exists() method .
对我来说,Sean A.O. Harney的回答和Cort3z的评论似乎是最好的解决方案。
使用以下代码段:
File f = new File(filePathString);
if(f.exists() && f.isFile()) {
//do something ...
}
希望这能帮助到一些人。