How to Check Path is existing or not in java?

2022-09-01 22:54:17

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?


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

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


答案 2

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

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