如何在java中检查Path是否存在?

raj*_*aja 23 java file-io

我有一个java程序,它以path作为参数.我想在进行其他验证之前检查给定路径是否存在.例如:如果我给出一个不存在的路径D:\ Log\Sample,它必须抛出filenotfound异常.我怎样才能做到这一点?

Zac*_*ena 27

if (!new File("D:\\Log\\Sample").exists())
{
   throw new FileNotFoundException("Yikes!");
}
Run Code Online (Sandbox Code Playgroud)

此外File.exists(),还有File.isDirectory()和File.isFile().

  • 请 - "抛出新的FileNotFoundException(f.getAbsolutePath())` (5认同)

Rom*_*las 12

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).
    ... 
}
Run Code Online (Sandbox Code Playgroud)


mP.*_*mP. 1

新文件(路径).exists()。

阅读 javadoc 非常有用,并且经常提供许多有用的示例。

  • 虽然我知道它是有帮助的,但我发现像“去阅读文档”这样的评论会适得其反。不要假设读者知道 javadoc 是什么或如何访问它们 (5认同)