In Java, there are multiple ways to check if a directory is empty or not. If you are using Java 7 or higher, you can use Files.list() method to check if a directory is empty:

try {
    // directory path
    Path path = Paths.get("dir");

    // check if directory is empty
    if (Files.isDirectory(path)) {
        if (!Files.list(path).findAny().isPresent()) {
            System.out.println("Dirctory is empty!");
        } else {
            System.out.println("Dirctory is not empty!");
        }
    } else {
        System.out.println("Not a directory!");
    }

} catch (IOException ex) {
    ex.printStackTrace();
}

Alternatively, you can also use File.list() from legacy I/O package to verify if a directory contains files or not as shown below:

// directory path
File file = new File("dir");

// check if directory is empty
if (file.isDirectory()) {
    String[] list = file.list();
    if (list == null || list.length == 0) {
        System.out.println("Dirctory is empty!");
    } else {
        System.out.println("Dirctory is not empty!");
    }
} else {
    System.out.println("Not a directory!");
}

Further Reading

You may be interested in other Java I/O articles:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.