在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
其他回答
不要在String中使用File构造函数。 这可能行不通! 而不是使用URI:
File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) {
// to do
}
使用java.io.File:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
通过在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
}
如果exists和notExists都返回false,则不能验证文件是否存在。(可能没有访问该路径的权限)
您可以检查path是目录还是普通文件。
if (Files.isDirectory(path)) {
// path is directory
}
if (Files.isRegularFile(path)) {
// path is regular file
}
请查看Java SE 7教程。
你可以使用以下方法:
第一次点击“java文件存在”在谷歌:
import java.io.*;
public class FileTest {
public static void main(String args[]) {
File f = new File(args[0]);
System.out.println(f + (f.exists()? " is found " : " is missing "));
}
}