23

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?

Zach Scrivena
  • 29,073
  • 11
  • 63
  • 73
raja
  • 4,043
  • 6
  • 30
  • 24
  • 3
    For Java 7+, [this](http://stackoverflow.com/questions/15571496/how-to-check-if-a-folder-exists) is the right way to do it. – elhefe May 24 '16 at 16:48

3 Answers3

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

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

Zach Scrivena
  • 29,073
  • 11
  • 63
  • 73
12

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).
    ... 
}
Romain Linsolas
  • 79,475
  • 49
  • 202
  • 273
1

new File( path ).exists().

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

mP.
  • 18,002
  • 10
  • 71
  • 105
  • 5
    While I know its meant to be helpful, I find comments like "go read the docs" counter productive. Don't assume the reader knows what javadocs is or how to access them – tatmanblue Jun 09 '15 at 15:32