Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we're going to get familiar with a few ways to find out if a directory is empty or not.

2. Using Files.newDirectoryStream

As of Java 7, the Files.newDirectoryStream method returns a DirectoryStream<Path> to iterate over all the entries in the directory. So we can use this API to check if the given directory is empty or not:

public boolean isEmpty(Path path) throws IOException {
    if (Files.isDirectory(path)) {
        try (DirectoryStream<Path> directory = Files.newDirectoryStream(path)) {
            return !directory.iterator().hasNext();
        }
    }

    return false;
}

For non-directory inputs, we'll return false without even trying to load the directory entries:

Path aFile = Paths.get(getClass().getResource("/notDir.txt").getPath());
assertThat(isEmpty(aFile)).isFalse();

On the other hand, if the input is a directory, we'll try to open a DirectoryStream to that directory. Then we'll consider the directory as empty if and only if the first hasNext() method call return false. Otherwise, it's not empty:

Path currentDir = new File("").toPath().toAbsolutePath();
assertThat(isEmpty(currentDir)).isFalse();

The DirectoryStream is a Closeable resource, so we're wrapping it inside a try-with-resources block. As we might expect, the isEmpty method returns true for empty directories:

Path path = Files.createTempDirectory("baeldung-empty");
assertThat(isEmpty(path)).isTrue();

Here we're using the Files.createTempDirectory to create an empty and temporary directory.

3. Using Files.list

As of JDK 8, the Files.list method uses the Files.newDirectoryStream API internally to expose a Stream<Path>. Each Path is an entry inside the given parent directory. Therefore, we can also use this API for the same purpose:

public boolean isEmpty(Path path) throws IOException {
    if (Files.isDirectory(path)) {
        try (Stream<Path> entries = Files.list(path)) {
            return !entries.findFirst().isPresent();
        }
    }
        
    return false;
}

Again, we're only touching the first entry using the findFirst method. If the returned Optional is empty, then the directory is empty, too.

The Stream is backed by an I/O resource, so we're making sure to release it appropriately using a try-with-resources block.

4. Inefficient Solutions

Both Files.list and Files.newDirectoryStream will iterate the directory entries lazily. Therefore, they will work with huge directories very efficiently. However, solutions like this will not work well in this scenario:

public boolean isEmpty(Path path) {
    return path.toFile().listFiles().length == 0;
}

This will eagerly load all the entries inside the directory which will be pretty inefficient when dealing with huge directories.

5. Conclusion

In this short tutorial, we got familiar with a few efficient ways to check whether a directory is empty or not.

As usual, all the examples are available over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
guest
0 Comments
Inline Feedbacks
View all comments