How to check if Directory exists in Java

2020-06-24 Java

This article was last updated on days ago, the information described in the article may be outdated.

In this post, we will see how to check if a directory exists in Java.

There are several ways to check for directory’s existence in Java. Each of below solutions returns true if directory exists; false otherwise.

Check if a File/Directory exists using Java IO’s File.exists()

import java.io.File;

public class CheckFileExists1 {
    public static void main(String[] args) {

        File file = new File("/Users/callicoder/demo.txt");

        if(file.exists()) {
            System.out.printf("File %s exists%n", file);
        } else {
            System.out.printf("File %s doesn't exist%n", file);
        }

    }
}

Check if a File/Directory exists using Java NIO’s Files.exists() or Files.notExists()

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

public class CheckFileExists {
    public static void main(String[] args) {

        Path filePath = Paths.get("/Users/callicoder/demo.txt");

        // Checking existence using Files.exists
        if(Files.exists(filePath)) {
            System.out.printf("File %s exists%n", filePath);
        } else {
            System.out.printf("File %s doesn't exist%n", filePath);
        }


        // Checking existence using Files.notExists
        if(Files.notExists(filePath)) {
            System.out.printf("File %s doesn't exist%n", filePath);
        } else {
            System.out.printf("File %s exists%n", filePath);
        }
    }
}

Author: Jovisom

Permalink: https://jovisom.com/how-to-check-if-directory-exists-in-java/

Java