How to Check if a Directory is Empty in Java

Learn to check if a directory is empty, or contains any files, in Java using NIO APIs.

1. Using Files.list()

The Files.list(dirPath) returns a lazily populated Stream of files and directories (non-recursive) in a given path. We can use the stream.findAny() method that returns an empty Optional if the directory is empty.

  • If the specified path is not a directory then NotDirectoryException is thrown.
  • The directory is closed by closing the stream.

This findAny() short-circuiting terminal operation that can conclude the result after selecting any element in the stream, so it does not need to look into the whole directory and its files before making a decision. It makes this approach a good solution with efficient performance for even the very large directories.

Path dirPath = Paths.get("C:/temp");

boolean isEmptyDirectory = Files.list(dirPath).findAny().isPresent();

2. Using DirectoryStream

A directory stream allows for the convenient use of the for-each construct to iterate over a directory.

A DirectoryStream is opened upon creation and is closed by invoking the close() method. Alternatively, we should use the try-with-resources statement that automatically closes the stream after use.

By using the iterator of the directory stream, we can call it’s hasNext() that checks if there is any file/directory element in the stream. If the directory is empty then hasNext() will return false.

Path dirPath = Paths.get("C:/temp");
boolean isEmptyDirectory = false;

if (Files.isDirectory(dirPath)) {
  try (DirectoryStream<Path> dirStream =
           Files.newDirectoryStream(dirPath)) {
    isEmptyDirectory = !dirStream.iterator().hasNext();

3. Conclusion

In this Java tutorial, we learned a few performance-proven methods to check if a given directory is empty or not. We are using the stream’s laziness behavior to improve the performance that otherwise is sometimes a very expensive operation in the case of large folders.

Happy Learning !!

Source Code on Github

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.