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.

package org.kodejava.example.nio;

import java.io.IOException;
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 stream = Files.newDirectoryStream(dir, "*.txt")) {
            for (Path entry : stream) {
                System.out.println(entry.getFileName());
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

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

I am a programmer, a runner, an open water diver and currently living in the island of Bali, Indonesia. If you need help on Java programming you can hire me on Fiverr.

Leave a Comment.