This article shows you how to check if a Path exists in Java.

Java Check if a Path Exists:

Java NIO package helps us to get this done.

Files.exists():

Files.exists(Path) method takes Path as a parameter and returns True if the given path exists, otherwise, its returns False.

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

public class IsPathExists {

        public static void main(String[] args) throws Exception {
            Path path = Paths.get("/Users/chandra/sample.txt");
            System.out.println("isPathExists: " + Files.exists(path));
        }
}

Output:

isPathExists: true

Files.notExists():

Files.notExists() is exactly reverse functionality of Files.exists(), it returns True if the provided path does not exist otherwise it’s False.

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

public class isPathExists {

        public static void main(String[] args) throws Exception {
            Path path = Paths.get("/Users/chandra/sample.txt");
            System.out.println("is Path notExists: " + Files.notExists(path));
        }
}

Output:

is Path notExists: false

References:

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment