如何检查路径是否存在或不在java中?
问题描述:
我有一个java路径作为参数的程序。我想在进行其他验证之前检查给定的路径是否存在。例如:如果我给出一个不存在的路径D:\ Log \ Sample,它必须抛出filenotfound异常。我怎样才能做到这一点?如何检查路径是否存在或不在java中?
答
new File(path).exists()。
阅读javadoc其非常有用,并且经常给出许多有用的示例。
+5
虽然我知道它的意思是有帮助的,但我发现诸如“去阅读文档”的反评论。不要假设读者知道javadoc是什么或者如何访问他们 – tatmanblue 2015-06-09 15:32:41
答
if (!new File("D:\\Log\\Sample").exists())
{
throw new FileNotFoundException("Yikes!");
}
+5
请 - `抛出FileNotFoundException(f.getAbsolutePath())` – 2011-05-10 19:48:07
答
类java.io.File中可以照顾,对你:
File f = new File("....");
if (!f.exists()) {
// The directory does not exist.
...
} else if (!f.isDirectory()) {
// It is not a directory (i.e. it is a file).
...
}
对于Java 7 +,[这](http://stackoverflow.com/questions/15571496/how-to-检查文件夹是否存在)是正确的方法。 – elhefe 2016-05-24 16:48:59