Java “file exists” testing

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

Solution: To see if a file exists in Java code, use the Java File.exists method. Here’s an example that shows the basic technique:

File tmpDir = new File("/var/tmp");   // create a File object
boolean exists = tmpDir.exists();     // call its 'exists' method

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.