How to Check if a File or a Directory Exists in Java

In Java, there are two primary methods of checking if a file or directory exists. These are:

1 - Files.exists from NIO package

2 - File.exists from legacy IO package

Let’s see some of the examples from each package.

Check if File Exists (Java NIO)

The code uses Path and Paths from the Java NIO package to check if a file exists:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CheckFileExist {

    public static void main(String[] args) {

        Path path = Paths.get("/path/to/file/app.log");

        if (Files.exists(path)) {

            if (Files.isRegularFile(path)) {
                System.out.println("App log file exists");
            }

        } else {
            System.out.println("App log file does not exists");
        }
    }
}

Check if Directory Exists (Java NIO)

Likewise, if we wanted to check if a directory exists in Java using the NIO package:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CheckDirectoryExist {

    public static void main(String[] args) {

        Path path = Paths.get("/path/to/logs/");

        if (Files.exists(path)) {

            if (Files.isDirectory(path)) {
                System.out.println("Logs directory exists");
            }

        } else {
            System.out.println("Logs directory does not exist");
        }
    }
}

Check if File Exists (Java Legacy IO)

If you’re not using Java NIO package, you can use the legacy Java IO package:

import java.io.File;

public class CheckFileExists {

    public static void main(String[] args) {

        File file = new File("/path/to/file/app.log");

        if(file.exists()) {
            System.out.println("App log file exists");
        } else {
            System.out.println("App log file does not exist");
        }
    }
}

Check if Directory Exists (Java Legacy IO)

Similarly, to check directory we can use:

import java.io.File;

public class CheckFileExists {

    public static void main(String[] args) {

        File file = new File("/path/to/logs/");

        if(file.isDirectory()) {
            System.out.println("Logs directory exists");
        } else {
            System.out.println("Logs directory does not exist");
        }
    }
}

Further reading