我有一个接受路径作为参数的Java程序。在进行其他验证之前,我想检查给定的路径是否存在。例如:如果我给出路径D:\Log\Sample,它不存在,那么它就会抛出filenotfound异常。我该如何做到这一点?
if (!new File("D:\\Log\\Sample").exists())
{
throw new FileNotFoundException("Yikes!");
}
throw new FileNotFoundException(f.getAbsolutePath())
。该代码会抛出一个文件未找到的异常,并将文件路径作为异常信息。 - Thorbjørn Ravn AndersenJava的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).
...
}
new File( path ).exists().
阅读javadoc非常有用,通常会提供许多有用的示例。