How do I find files in a directory using DirectoryStream?

In this example we are going to learn to use the DirectoryStream, which part of java.nio.file package, to find files in a directory. We are begin by creating a Path, the directory where the search will be conducted.

After that we create a DirectoryStream using Files.newDirectoryStream(). To create a directory stream we passed two arguments, the starting path and a glob expression. Below we use *.txt glob expression to filter all text files in the D:/Workbench.

To get all the entries of the directory stream we can use a foreach loop as can be seen below. We iterate each entries, which is a Path object. And we print the entries file name using the getFileName() method.


import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FindFilesInDirectory {
    public static void main(String[] args) {
        Path dir = Paths.get("D:/Workbench");

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.txt")) {
            for (Path entry : stream) {
        } catch (IOException e) {

You can also notice that in this example we are using the try-with-resource statement. This mean that the DirectoryStream will be closed appropriately when the process is done. This type of try statement is an improvement introduced in JDK 7.

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. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

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