在Java中(相当于Perl的-e $filename)打开文件读取之前,如何检查文件是否存在?
SO中唯一类似的问题涉及写入文件,因此使用FileWriter来回答,这显然不适用于这里。
如果可能的话,我更喜欢一个真正的API调用返回true/false,而不是一些“调用API打开一个文件,并在它抛出一个异常时捕获你检查文本中的‘无文件’”,但我可以接受后者。
在Java中(相当于Perl的-e $filename)打开文件读取之前,如何检查文件是否存在?
SO中唯一类似的问题涉及写入文件,因此使用FileWriter来回答,这显然不适用于这里。
如果可能的话,我更喜欢一个真正的API调用返回true/false,而不是一些“调用API打开一个文件,并在它抛出一个异常时捕获你检查文本中的‘无文件’”,但我可以接受后者。
当前回答
你可以这样做
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()可以用来检查这样的文件是否存在。
f.isFile() && f.canRead()
使用java.io.File:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
如果使用spring框架,文件路径以classpath开头:
public static boolean fileExists(String sFileName) {
if (sFileName.startsWith("classpath:")) {
String path = sFileName.substring("classpath:".length());
ClassLoader cl = ClassUtils.getDefaultClassLoader();
URL url = cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path);
return (url != null);
} else {
Path path = Paths.get(sFileName);
return Files.exists(path);
}
}
使用Java 8:
if(Files.exists(Paths.get(filePathString))) {
// do something
}