In this section we will be showing a java sample source code that check if the folder is empty or not. This example shows as well how to check if folder exists or not and check as well if it is a directory.

Check directory if empty in java

This example source code use the method list() of File class. The output of this method is an array of String that is files under the specified folder declared in the constructor of the File class. This would enable us then to check if the directory is empty.

package com.javatutorialhq.tutorial;

import java.io.File;

public class CheckDirectoryEmpty {

	/**
	 * This sample code shows
	 * how to check if folder is empty or not
	 * Property of javatutorialhq.com
	 * All Rights Reserved
	 * Version 1.0
	 * 07/01/2012
	 */

	public static void main(String[] args) {
		File f = new File("C:\\temp");
		if(f.isDirectory() && f.exists()){
			if(f.list().length > 0);
				System.out.println("Directory is not empty");
			}
			else{
				System.out.println("Directory is empty");
			}
		}
		else{
			System.out.println("Please check folder, either empty or does not exists");
		}

	}

}
[/sourcecode]

Sample Output:

Directory is not empty

The directory C:\temp on my machine is not empty thus the output in running the program will be “Directory is not empty”. Output will differ on your machine as well depending on what is the filename that you declared in calling the File class.