【问题标题】:How to Check Path is existing or not in java?如何检查路径是否存在于java中?
【发布时间】:2009-01-28 10:39:33
【问题描述】:

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

【问题讨论】:

  • 对于 Java 7+,this 是正确的做法。

标签: java file-io


【解决方案1】:
if (!new File("D:\\Log\\Sample").exists())
{
   throw new FileNotFoundException("Yikes!");
}

除了File.exists(),还有File.isDirectory()File.isFile()

【讨论】:

  • 请-throw new FileNotFoundException(f.getAbsolutePath())
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 虽然我知道它是有帮助的,但我发现像“去阅读文档”这样的 cmets 会适得其反。不要假设读者知道 javadocs 是什么或如何访问它们
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 2020-02-28
    • 2011-02-04
    相关资源
    最近更新 更多