在Java中(相当于Perl的-e $filename)打开文件读取之前,如何检查文件是否存在?
SO中唯一类似的问题涉及写入文件,因此使用FileWriter来回答,这显然不适用于这里。
如果可能的话,我更喜欢一个真正的API调用返回true/false,而不是一些“调用API打开一个文件,并在它抛出一个异常时捕获你检查文本中的‘无文件’”,但我可以接受后者。
在Java中(相当于Perl的-e $filename)打开文件读取之前,如何检查文件是否存在?
SO中唯一类似的问题涉及写入文件,因此使用FileWriter来回答,这显然不适用于这里。
如果可能的话,我更喜欢一个真正的API调用返回true/false,而不是一些“调用API打开一个文件,并在它抛出一个异常时捕获你检查文本中的‘无文件’”,但我可以接受后者。
当前回答
我知道我在这个话题上有点晚了。然而,这是我的答案,自Java 7及更高版本起有效。
下面的代码片段
if(Files.isRegularFile(Paths.get(pathToFile))) {
// do something
}
是完全令人满意的,因为如果文件不存在,方法isRegularFile返回false。因此,不需要检查Files.exists(…)。
注意,其他参数是指示应如何处理链接的选项。默认情况下,使用符号链接。
来自Java Oracle文档
其他回答
熟悉Commons FileUtils https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html也是非常值得的 它有额外的管理文件的方法,通常比JDK更好。
我知道我在这个话题上有点晚了。然而,这是我的答案,自Java 7及更高版本起有效。
下面的代码片段
if(Files.isRegularFile(Paths.get(pathToFile))) {
// do something
}
是完全令人满意的,因为如果文件不存在,方法isRegularFile返回false。因此,不需要检查Files.exists(…)。
注意,其他参数是指示应如何处理链接的选项。默认情况下,使用符号链接。
来自Java Oracle文档
你可以使用以下方法:
f.isFile() && f.canRead()
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 .