This post will discuss how to check if a file exists in Java.

When you are testing a file’s existence, three results are possible:

  • The file exists.
  • The file doesn’t exist.
  • The file’s status is unknown as the program does not have access to the file.

 
There are several ways to check for a file’s existence in Java. Each of the following solutions returns true if the file exists; false otherwise, when the file doesn’t exist or the file’s status is unknown.

1. Using File.exists() method

The idea is to use the File.exists() method to determine whether a file denoted by a specified pathname exists. This method returns true if the file exists; false otherwise.

Note that File.exists() returns true when your path points to a directory. So, it is recommended to call this method along with the File.isDirectory() method, which checks for a directory. This is demonstrated below:

Download Code

 
Please note that when operating on NFS-mounted volumes, java.io.File.exists sometimes returns false even though the file referenced actually does exist. See bug details here.

2. Using File.isFile() method

We have seen that File.exists() returns true if your path points to a directory. To explicitly avoid checking for a directory, it is recommended to use File.isFile() method instead of File.exists() method. The File.isFile() method tests whether the file denoted by the specified path is a normal file, i.e., the file is not a directory.

Download Code

3. Using NIO

From Java 7 onward, we can use java.nio.file.Files, which provides several static methods that operate on files, directories, or other types of files. To simply check for a file’s existence, we can use exists() and notExists() method of java.nio.file.Files class. The exists() method returns true if the file exists, whereas the notExists() method returns true when it does not exist. If both exists() and notExists() return false, the existence of the file cannot be verified. This can happen when the program does not have access to the file.

Note that Files.exists() returns true when your path points to a directory. So, it is recommended to use this method along with the Files.isDirectory() method, which checks the file for a directory. This is demonstrated below:

Download Code

 
Alternatively, we can check if a path is a regular file (and not a directory) using the Files.isRegularFile() method:

Download Code

That’s all about determining whether a file exists in Java.