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?
Asked
Active
Viewed 5.9k times
23
-
3For 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 Answers
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
-
5Please - `throw new FileNotFoundException(f.getAbsolutePath())` – Thorbjørn Ravn Andersen May 10 '11 at 19:48
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
-
5While 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