How to Check If a Folder Is Empty in Java


In this example we will show how to check if a folder is empty in Java.

Source Code

package com.beginner.examples;

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

public class CheckEmptyDirector {

  public static void main(String[] args) throws IOException {
    File dir = new File("Test");
    if(dir.isDirectory()) {
      String[] dirs = dir.list();
      if(dirs.length == 0) { // check if a folder is empty
        System.out.println("This folder is empty.");
      } else {
        System.out.println("This folder is not empty.");
      }
    }
}

Output:

This folder is empty.

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments