How to check if directory is empty in Java
check
directory
empty
Here is a simple example how to check if a directory is empty in Java.
Example
The example is using list() method of File class.
package com.admfactory.io;
import java.io.File;
public class DirectoryCheck {
public static void main(String[] args) {
System.out.println("Check Directory Example");
System.out.println();
File file = new File("D:\\admfactory.com\\dir1");
if (file.isDirectory()) {
if (file.list().length > 0) {
System.out.println("Directory '" + file.getAbsolutePath() + "' is not empty!");
} else {
System.out.println("Directory '" + file.getAbsolutePath() + "' is empty!");
}
} else {
System.out.println("'" +file.getAbsolutePath() + "' is not a directory");
}
}
}
Output
Check Directory Example
Directory 'D:\admfactory.com\dir1' is not empty!