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.
1 |
public boolean exists() |
This method returns true if the file represented by the given path exists, false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.javacodeexamples.ioexamples; import java.io.File; public class CheckFileExistsExample { public static void main(String[] args){ File file = new File("c:/somefile.txt"); if( file.exists() ){ System.out.println("File exists"); }else{ System.out.println("File does not exist"); } } } |
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
1 2 3 4 5 6 |
File file = new File("C:/dir"); if( file.exists() ){ System.out.println("Directory exists"); }else{ System.out.println("Directory does not exist"); } |
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.
1 2 3 4 5 6 7 |
File file = new File("c:/somefile.txt"); if( file.exists() && !file.isDirectory()){ System.out.println("File exists"); }else{ System.out.println("File does not exist"); } |
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.
1 |
public boolean isFile() |
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).
1 2 3 4 5 6 7 |
File file = new File("c:/somefile.txt"); if( file.isFile() ){ System.out.println("File exists"); }else{ System.out.println("File does not exist"); } |
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).
1 2 3 4 5 6 7 |
File file = new File("c:/somefile.txt"); if( file.isFile() && file.canRead() ){ System.out.println("File exists and it is readable"); }else{ System.out.println("File does not exist or no read permission"); } |
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.