如何在java中检查路径是否存在?
我有一个以路径为参数的java程序。在进行其他验证之前,我想检查给定路径是否存在。例如:如果我给出一个不存在的路径D:\Log\Sample,它必须抛出filenotfound异常。我如何才能做到这一点?新文件(路径).exists() 阅读javadoc,它非常有用,并经常给出许多有用的例子如何在java中检查路径是否存在?,java,file-io,Java,File Io,我有一个以路径为参数的java程序。在进行其他验证之前,我想检查给定路径是否存在。例如:如果我给出一个不存在的路径D:\Log\Sample,它必须抛出filenotfound异常。我如何才能做到这一点?新文件(路径).exists() 阅读javadoc,它非常有用,并经常给出许多有用的例子 if (!new File("D:\\Log\\Sample").exists()) { throw new FileNotFoundException("Yikes!"); } 此外,还有和。类
if (!new File("D:\\Log\\Sample").exists())
{
throw new FileNotFoundException("Yikes!");
}
此外,还有和。类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).
...
}
请-
抛出新的FileNotFoundException(f.getAbsolutePath())
虽然我知道这是有帮助的,但我发现像“阅读文档”这样的评论会适得其反。不要假设读者知道什么是javadocs,或者如何访问Java7+,这是正确的方法。