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



The code actually does not work as specified - it will check if a _file/directory_ exists, and if not, create a directory of this name. So it will not work if I have a regular old file with the name of the desired directory.

The if condition should read if (!theDir.exists() || !file.isDirectory()) { ...

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.