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


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.

Example

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
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) {
         System.out.println(fileName.getName());
         System.out.println(fileName);

      }  
   }
}

Output

List of the jpeg files in the specified directory:
sample directory1
D:\ExampleDirectory\sample directory1

Updated on: 08-Feb-2021

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements