如何检查路径在java中是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/487181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:16:17  来源:igfitidea点击:

How to Check Path is existing or not in java?

javafile-io

提问by raja

I have a java program which take path as argument. I want to check whether given path is existing or not before doing other validation. Eg: If i give a path D:\Log\Sample which is not not exist, it has to throw filenotfound exception. How can i do that?

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

回答by mP.

new File( path ).exists().

新文件(路径)。存在()。

Read the javadoc its very useful and often gives many useful examples.

阅读 javadoc 非常有用,并且经常给出很多有用的例子。

回答by Zach Scrivena

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

Besides File.exists(), there are also File.isDirectory()and File.isFile().

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

回答by Romain Linsolas

The class java.io.File can take care of that for you:

类 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).
    ... 
}