Check if a directory exists in Java
This post will discuss how to check if a directory exists in Java.
There are several ways to check for the directory’s existence in Java. Each of the following solutions returns true if the directory exists; false otherwise.
1. Using File.isDirectory() method
The idea is to use the File.isDirectory() method to determine whether the file denoted by a specified path is a directory. This method returns true if the directory exists; false otherwise. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.io.File; class Main { public static void main(String[] args) { String directoryPath = "/var/www/html/"; File file = new File(directoryPath); if (file.isDirectory()) { System.out.println("File is a Directory"); } else { System.out.println("Directory doesn't exist!!"); } } } |
2. Using NIO
From Java 7 onward, we can use java.nio.file.Files, which provides several static methods that operate on files, directories, or other types of files. To simply check for a directory’s existence, we can use isDirectory() method of java.nio.file.Files class. The Files.isDirectory() returns true when your path points to a directory. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; class Main { public static void main(String[] args) { String directoryPath = "/var/www/html/"; Path path = Paths.get(directoryPath); boolean isDir = Files.isDirectory(path); if (isDir) { System.out.println("File is a Directory"); } else { System.out.println("Directory doesn't exist!!"); } } } |
That’s all about determining whether a directory exists in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)