Skip to content

Check if file exists in Java

This example shows how to check if a file exists in Java using the exists method of the Java File class. The exists method returns true if the file exists.

How to check if the file exists in Java?

It is a good practice to check if the file exists before opening it to read it. This check can be done using the exists method of the 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 the File object contains a path of a directory and if it exists, the exists method will return true.

Example

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

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

Another alternative to check is to use the isFile method.

The 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 the canRead method along with the isFile method to make sure that the file exists and can be readable (the application has read permission for the file).

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

This example is a part of the Java File class tutorial with examples.

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

About the author

Leave a Reply

Your email address will not be published.