Check if the directory is empty or not


 

Check if the directory is empty or not

In this section, you will learn how to check if the directory is empty or not.

In this section, you will learn how to check if the directory is empty or not.

Check if the directory is empty or not

In this section, you will learn how to check if the directory is empty or not.

Java IO package works with both files and directories. Here we are going to check whether directory is empty or not. For this, we have created an instance of File class and specify the directory path in the constructor of the File class. Then we have called isDirectory() method to check whether the pathname of the object represented by a File object is a directory. If it is a directory then we have called the method list() of array type which return the array of files and directories. If the length of this array is not zero, the directory is considered as non empty.

Here is the code:

import java.io.File;

public class CheckDirectory {
	public static void main(String[] args) {
		File file = new File("C:/Hello/");
		if (file.isDirectory()) {
			String[] files = file.list();
			if (files.length > 0) {
				System.out.println(file.getPath() + " is not empty.");
			}
		}
	}
}

Through the above code, you can check whether the specified directory is empty or not.

Output:

C:\Hello is not empty.

Ads