Java File IO: How to test whether a file or directory exists

Java File I/O FAQ: Using Java, how can you test to see if a file or directory exists?

The short story is that you begin by using the exists() method of the java.io.File class, like this:

File file = new File("foo");

if (file.exists()) {
    System.out.println("a file or directory named 'foo' exists");
}

To determine whether this “file” is really a file or a directory, you need to add the isFile() and isDirectory() tests. You can write this code in many different ways, but this code shows a general approach:

if (file.exists()) {
    if (file.isFile()) {
        System.out.println("'foo' exists and it is a file");
    } else if (file.isDirectory()) {
        System.out.println("'foo' exists and it is a directory");
    }
}

I didn’t run that code through a compiler, but if it doesn’t compile I hope it’s close enough to show you the solution.

In summary, if you wanted to see how to test to see if a file or directory exists in your Java code, I hope this helps.

(Many thanks to the person who left the first comment below, who got me to correct this post.)