在Java中(相当于Perl的-e $filename)打开文件读取之前,如何检查文件是否存在?

SO中唯一类似的问题涉及写入文件,因此使用FileWriter来回答,这显然不适用于这里。

如果可能的话,我更喜欢一个真正的API调用返回true/false,而不是一些“调用API打开一个文件,并在它抛出一个异常时捕获你检查文本中的‘无文件’”,但我可以接受后者。


当前回答

设计这些方法是有特定目的的。我们不能说使用任何人来检查文件是否存在。

isFile():测试由这个抽象路径名表示的文件是否是一个正常的文件。 exists():测试由此抽象路径名表示的文件或目录是否存在。 docs.oracle.com

其他回答

有多种方法可以实现这一点。

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

我知道我在这个话题上有点晚了。然而,这是我的答案,自Java 7及更高版本起有效。

下面的代码片段

if(Files.isRegularFile(Paths.get(pathToFile))) {
    // do something
}

是完全令人满意的,因为如果文件不存在,方法isRegularFile返回false。因此,不需要检查Files.exists(…)。

注意,其他参数是指示应如何处理链接的选项。默认情况下,使用符号链接。

来自Java Oracle文档

不要在String中使用File构造函数。 这可能行不通! 而不是使用URI:

File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) { 
    // to do
}

你可以这样做

import java.nio.file.Paths;

String file = "myfile.sss";
if(Paths.get(file).toFile().isFile()){
    //...do somethinh
}
File f = new File(filePathString); 

这将不会创建物理文件。只会创建File类的对象。要物理创建一个文件,你必须显式地创建它:

f.createNewFile();

因此f.exists()可以用来检查这样的文件是否存在。