File
Check if directory exists
In this example we shall show you how to check if a directory exists. We are using the File class that is an abstract representation of file and directory pathnames. To check if a directory exists one should perform the following steps:
- Create a new File instance by converting the given pathname string into an abstract pathname.
- Use
exists()
API method of File. This method tests whether the file or directory denoted by this abstract pathname exists. It returns true if and only if the file or directory denoted by this abstract pathname exists and false otherwise,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.io.File; public class CheckIfDirectoryExists { public static void main(String[] args) { File dir = new File("C://directory"); // Tests whether the directory denoted by this abstract pathname exists. boolean exists = dir.exists(); System.out.println("Directory " + dir.getPath() + " exists: " + exists); } }
This was an example of how to check if a directory exists in Java.