How to check if directory is empty in Java

Here’s an example to check if a directory is empty.

Example


package com.mkyong.file;

import java.io.File;

public class CheckEmptyDirectoryExample
{
    public static void main(String[] args)
    {	

	File file = new File("C:\\folder");
		
	if(file.isDirectory()){
			
		if(file.list().length>0){
				
			System.out.println("Directory is not empty!");
				
		}else{
				
			System.out.println("Directory is empty!");
				
		}
			
	}else{
			
		System.out.println("This is not a directory");
			
	}
    }
}

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Sridhar
13 years ago

what if its a huge directory? it will take more time to list(), is there any other way without calling list() to find its empty??

Mitp
8 years ago

Trying to device logic to delete entire hierarchy of folders if there is no file available at lowest level. Any suggestions?

????? ???????
10 years ago

Thanks!!!

Ilir
11 years ago

You are awesome Mkyong. Any topic you do not have any tutorial for?

Shubhashish Bhowmik
16 years ago

Good example