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");
 
	}
    }
}
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments