Java IO

Check if file exists in Java

Sometimes we want to check if file exists before opening it for reading. Java File class provides exists() method to check that.

How to check if file exists in Java?

It is good practice to check if the file exists before opening it to read it. This check can be done using exists() method of java.io.File class.

This method returns true if the file represented by the given path exists, false otherwise.

Java File object represents both files as well as directories. So, if File object contains a path of a directory and if it exists, exists() method will return true.

For example,

In this case, if the file is a directory and an attempt is made to open it for reading, it will throw IOException. Good practice is to check whether the file exists and it is not a directory before opening it for reading.

Note: exists() and isDirectory() methods may throw java.lang.SecurityException, if read permission is denied for the file or directory.

Other alternative to check if file exists is to use isFile() method

isFile() method returns true if and only if the file represented by the path exists and it is a normal file (not a directory).

You can also use canRead() method along with the isFile() method to make sure that the file exists and can be readable (application has read permission for the file).

Note:  isFile() and canRead() methods may throw java.lang.SecurityException, if access is denied to read the file or directory.

Please let us know your views in the comments section below.

Tags
Join 1000+ fellow learners! Enter your email address below: