How to get the names of the empty directories in a directory in Java?

JavaServer Side ProgrammingProgramming

The ListFiles() method returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.

The File Filter interface is filter for the path names you can pass this as a parameter to the listFiles() method. This method filters the file names passed on the passed filter.

To get the directories in a folder implement a FileFilter which accepts only empty directories, and pass it as a parameter to the listFiles() method.


public class MyExample{
   public static void main(String args[]) throws IOException {
    //Creating a File object for directory
    File directoryPath = new File("D:\\ExampleDirectory");
    //Creating filter for directories files
    FileFilter fileFilter = new FileFilter(){
         public boolean accept(File dir) {          
            if (dir.isDirectory()&& dir.list().length==0) {
               return true;
            } else {
               return false;
      File[] list = directoryPath.listFiles(fileFilter);
      System.out.println("List of the jpeg files in the specified directory:");  
      for(File fileName : list) {



List of the jpeg files in the specified directory:
sample directory1
D:\ExampleDirectory\sample directory1
Published on 08-Feb-2021 11:16:11