Java Examples - Check if Directory is Empty
The following example demonstrates using the File class'sfile.isDirectory()andfile.list()method to check whether the directory is empty:
Main.java file
import java.io.File;
public class Main
{
public static void main(String[] args)
{
File file = new File("./testdir"); //The testdir directory in the current directory
if(file.isDirectory()){
if(file.list().length>0){
System.out.println("The directory is not empty!");
}else{
System.out.println("The directory is empty!");
}
}else{
System.out.println("This is not a directory!");
}
}
}
The output of running the above code is:
目录 D://Java/file.txt 不为空!Other Extensions
Java Examples