Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Check if a file exists in Java

In this post, we are going to check whether the file exists at the specified location or path. We are using Java code to check the presence of the specified file.

The exists() method of File class is used to tests whether the file or directory denoted by the path exists or not. It can be used to check the existent of both files and directories as well.

This method returns true if a file or directory exists. We can use the isFile() method to check the existing file is a file only not a directory.

Here, we have some examples in which we are using exists() and isFile() method as well.

Time for an Example:

Let's take an example to check if the file is present or not. Here, we are using exists() method that returns true if the file is present, false otherwise. See the example below.

import java.io.File;
import java.io.IOException;
public class Main {
	public static void main(String[] args) throws IOException{
		try {
		File file = new File("path/to/file/abc.txt");
        boolean isexist = file.exists();
        if(isexist) {
        	System.out.println("File is present");
        }else {
        	System.out.println("File does not present");
        }
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}


File is present

Time for another Example:

Let's take another example to check whether the file is present or not.

Here, we are using isFile() method with exists() method to ensure that the existing file is a file, not a directory. The isFile() method returns true if the existing file is a file, false otherwise.

import java.io.File;
import java.io.IOException;
public class Main {
	public static void main(String[] args) throws IOException{
		try {
		File file = new File("path/to/file/abc.txt");
        boolean isExist = file.exists();  // Check for valid path
        boolean isFile  = file.isFile();  // Check for file
        if(isExist && isFile) {
        	System.out.println("File is present");
        }else {
        	System.out.println("File does not present");
        }
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}


File is present