How do I check if a directory is not empty?

package org.kodejava.example.io;

import java.io.File;

public class EmptyDirCheck {
    public static void main(String[] args) {
        File file = new File("C:/Users/kodejava/Documents");

        // Check to see if the object represent a directory.
        if (file.isDirectory()) {
            // Get list of file in the directory. When its length is not zero
            // the folder is not empty.
            String[] files = file.list();

            if (files != null && files.length > 0) {
                System.out.println("The " + file.getPath() + " is not empty!");
            }
        }
    }
}

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support my work by donating here. Thank you.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.