Home »
Java programming language
How to check if directory exists in Java?
Checking directly exists or not: Here, we are going to learn how to check if directory exists in java?
Submitted by Preeti Jain, on July 03, 2019
- We are using the File class that is an abstract representation of file and directory path. To check if a directory exists we have to follow a few steps:
- Create a File object and at the time of instantiation, we have to give abstract path there for which we will be in searching.
- By using exists() method of File. This method tests whether the directory exists. The return type of this method is boolean so it returns true if and only if the directory exists and otherwise it will return false.
- We will understand clearly with the help of an example.
Example:
import java.io.File;
public class ToCheckDirectoryExists {
public static void main(String[] args) {
File dir_path1 = new File("C:\\Users\\computer clinic\\OneDrive\\Articles");
File dir_path2 = new File("C:\\Users\\computer clinic\\Articles");
// By using exists() method of File will check whether the
// specified directory exists or not and exist() method works
// with File class object because of its File method and
// it return Boolean return true if directory exists false otherwise.
boolean dir_exists1 = dir_path1.exists();
boolean dir_exists2 = dir_path2.exists();
// By using getPath()method to retrieve the given path of the
// directory and dir_exists1 and dir_exists1 returns true
// when directory exists else false.
System.out.println("Given Directory1 " + dir_path1.getPath() + " exists: " + dir_exists1);
System.out.println("Given Directory2 " + dir_path2.getPath() + " is not exists: " + dir_exists2);
}
}
Output
D:\Programs>javac ToCheckDirectoryExists.java
D:\Programs>java ToCheckDirectoryExists
Given Directory1 C:\Users\computer clinic\OneDrive\Articles exists: true
Given Directory2 C:\Users\computer clinic\Articles is not exists: false