Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Check if the file is a directory

In this post, we are going to check whether a directory exists at the specified location or path. The java.io.File and java.nio.Files class both provides methods to check the directory.

The isDirectory() method belongs to File class and returns true if the directory is present. Whereas Files class provides a static method isDirectory() that takes the path of the directory as an argument.

Here, we have created examples that use both the classes File and Files to Check the directory.

Time for an Example:

Let's take an example, to check whether the directory exists or not. Here, we are using the isDirectory() method of the File class that returns either true or false.

import java.io.File;
import java.io.IOException;
public class Main {
	public static void main(String[] args) throws IOException{
		try {
		File file = new File("path/to/directory/");
        boolean isDirectory  = file.isDirectory();  // Check for directory
        if(isDirectory) {
        	System.out.println("It is a directory");
        }else {
        	System.out.println("It is not directory");
        }
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}


It is a directory

Time for another Example:

Let's create another example to check the directory. Here, we are using the isDirectory() method of Files class that requires the path of the directory and returns true if path belongs to a directory, false otherwise.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
	public static void main(String[] args) throws IOException{
		try {
			Path path = Paths.get("path/to/directory/");
			boolean isDirectory  = Files.isDirectory(path);  // Check for directory
			if(isDirectory) {
				System.out.println("It is a directory");
			}else {
				System.out.println("It is not directory");
			}
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}


It is a directory