Java File exists()

In this guide, you will learn about the File exists() method in Java programming and how to use it with an example.

1. File exists() Method Overview


The exists() method in the File class is used to determine whether a file or directory denoted by this abstract pathname actually exists in the file system.


public boolean exists()



Key Points:

- The method returns true if the file or directory denoted by this abstract pathname exists; false otherwise.

- It is a commonly used method before performing operations like reading or writing to a file to avoid exceptions.

- This method can also be used to check if a directory exists.

- It doesn't differentiate between files and directories. It just checks for the existence.

- Ensure you have proper permissions (read permissions) to access the file or directory, as lacking them might return false even if the file exists.

2. File exists() Method Example


public class FileExistsExample {
    public static void main(String[] args) {
        // Specify the path of the file/directory
        File file = new File("sample.txt");

        // Check if the file or directory exists
        if (file.exists()) {
            System.out.println("File or directory exists!");
        } else {
            System.out.println("File or directory does not exist.");


(File or directory exists)
File or directory exists!

(File or directory does not exist)
File or directory does not exist.


In the provided example, we attempt to check the existence of a file or directory named "sample.txt" in the current directory. If the file or directory exists, "File or directory exists!" is printed. If it doesn't exist, "File or directory does not exist." is displayed. 

This method is quite handy to ensure that a file or directory is present before trying to perform operations on it, hence preventing potential runtime exceptions.