Share this page 

Check if a directory is empty Tag(s): IO


import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

public class FileUtils {
   public static void main(String[] args) throws IOException {
      //String folder = "c:/temp";
      String folder = "c:/temp/foo";

      System.out.println
          ("Folder " + folder + " empty ? " + FileUtils.isDirectoryEmpty(folder) );
   }

   public static Boolean isDirectoryEmpty(String directoryName) throws IOException {
      File [] content =
          new File(directoryName).listFiles
               (new  FilenameFilter() {
                    public boolean accept(File f, String s) {
                        return true;  // accept anything
               }});

      if (content == null) {
         throw new IOException(directoryName + " is not found.");
      }
      return (content.length == 0);
   }
}
To check for a specific extension then replace
                        return true;  // accept anything
by
                        return s.toLowerCase().endsWith(".txt"); // accept "*.txt"