Java ‘file exists’ testing

Java file FAQ: How can I test to see if a file or directory exists in Java?

Solution: The Java File exists method

To test to see if a file or directory exists, use the exists method of the Java File class, as shown in this example:

File tmpDir = new File("/var/tmp");
boolean exists = tmpDir.exists();

The exists method of the Java File class returns true if the file or directory exists, and false otherwise.

Test to see if the “file” is a file or directory

In a related note, if you’re working with directories, you may also want to test whether the “file” you’re looking at is really a directory, as shown in this example code:

if (tmpDir.isDirectory()) System.out.println("/var/tmp is a directory");

Similarly you can test to see if a file is truly a file (and not a directory), like this:

if (someFile.isFile()) System.out.println("someFile is a file");

A complete file/directory exists example

Putting it all together, here is an example that tests to see if a file exists, and whether or not that file is also a directory:

import java.io.File;

public class JavaFileDirectoryExistsExample
{
  public static void main(String[] args)
  {
    // test "/var/tmp" directory
    File tmpDir = new File("/var/tmp");
    boolean exists = tmpDir.exists();
    if (exists) System.out.println("/var/tmp exists");
    
    if (tmpDir.isDirectory()) System.out.println("/var/tmp is a directory");

    // test to see if a file exists
    File file = new File("/Users/al/.bash_history");
    exists = file.exists();
    if (file.exists() && file.isFile())
    {
      System.out.println("file exists, and it is a file");
    }
  }
}

As shown at the end of that example, you can also combine those tests like this:

if (tmpDir.exists() && tmpDir.isDirectory() )
{
  // you know it is a directory and it exists
  // your logic here ...
}

Summary

I hope these Java “file exists” tests are helpful. As usual, if you have any questions or comments, just leave them in the comments section below.

Add new comment

Anonymous format

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