Java

Java – How to Check if a Path Exists ?

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 :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment