How to check empty directory in java

This example shows you how to check a directory is empty or not in java.

To check the a directory is empty or not, you need to get the list of directory for File object, and check if the length of list is greater than 0 or not.

Below is the example code for checking empty directory in java.

package com.java.connect.io;

import java.io.File;

//How to check empty directory in java
public class EmptyDirectoryExample{
	public static void main(String[] args) {

		// Get the File object
		File file = new File("C:\\Program Files");

		// Check if the file is directory.
		if (file.isDirectory()) {
			// To check for directory is empty or not.
			// You can get the list of file inside the
			// directory and check the length of returns array.

			// Get files inside directory
			String[] files = file.list();
			// Check the length of array
			if (files.length > 0) {
				System.out.println("Its not an empty directory");
			} else {
				System.out.println("Its an empty directory");
			}
		}
	}
}

The output of the above example will be as:

Its not an empty directory