Java Files newDirectoryStream() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
Java 7+

Definition

In Java, Files.newDirectoryStream(dir) opens a DirectoryStream<Path>, an Iterable over the entries directly inside dir. You loop over it with for-each and close it with try-with-resources.

Two overloads filter the entries: a glob string such as "*.txt", or a DirectoryStream.Filter with your own code. Entries come in no particular order, and the stream can be iterated only once.

A static method of the final utility class java.nio.file.Files, available since Java 7. Call it on the class name, as in Files.newDirectoryStream(...), after import java.nio.file.Files;. You never create a Files object.

Syntax

All entries, a glob, or a filter:

Java
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{jpg,png}")) {
    for (Path entry : stream) {
        System.out.println(entry.getFileName());
    }
}
CallWhat it does
Files.newDirectoryStream(dir)Every entry.
Files.newDirectoryStream(dir, "*.txt")Names matching a glob.
Files.newDirectoryStream(dir, filter)Entries your Filter accepts.

Since Java 7. Glob syntax: * any characters, ? one character, {a,b} alternatives, [abc] a set. Whether matching ignores case depends on the file system (case-insensitive on Windows).

Library declarations
Java
public static DirectoryStream<Path> newDirectoryStream(Path dir) throws IOException
public static DirectoryStream<Path> newDirectoryStream(Path dir, String glob) throws IOException
public static DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) throws IOException

Parameters

ParameterDescription
dirThe folder to read.
globA glob pattern for entry names.
filterDecides which entries to return.

Return Value

Return ValueDescription
DirectoryStream<Path>An open, single-use stream of entries.

Compare with Similar Methods

One-level listings:

MethodHow it differs
list()Java 8 Stream of the same entries.
find()Recursive search with a condition.
walkFileTree()Java 7 recursive visitor.

Java Examples

Example 1 — Loop Over a Folder and Sort the Names

Collect the entry names into a list, sort them, and mark folders with a slash.

Java
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class NewDirectoryStreamLoop {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Files.write(dir.resolve("b.txt"), new byte[0]);
        Files.write(dir.resolve("a.txt"), new byte[0]);
        Path pics = Files.createDirectory(dir.resolve("pics"));
        List<String> names = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            for (Path entry : stream) {
                String name = entry.getFileName().toString();
                names.add(Files.isDirectory(entry) ? name + "/" : name);
            }
        }
        Collections.sort(names);
        System.out.println(names);
        Files.delete(pics);
        Files.delete(dir.resolve("a.txt"));
        Files.delete(dir.resolve("b.txt"));
        Files.delete(dir);
    }
}

How It Works

  1. An Iterable. DirectoryStream works directly in a for-each loop, which is why it fits Java 7 code without streams.
  2. Label folders. Files.isDirectory(entry) adds a slash to pics so it stands out.
  3. Sort after collecting. b.txt was created first, but entry order is unspecified, so the sorted list is the reliable result.

Example 2 — Pick Only Images with a Glob

The pattern *.{jpg,png} matches names ending in .jpg or .png.

Java
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class NewDirectoryStreamGlob {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        String[] names = {"cat.jpg", "dog.png", "notes.txt", "jpg"};
        for (String n : names) {
            Files.write(dir.resolve(n), new byte[0]);
        }
        List<String> images = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{jpg,png}")) {
            for (Path entry : stream) {
                images.add(entry.getFileName().toString());
            }
        }
        Collections.sort(images);
        System.out.println("Images: " + images);
        for (String n : names) {
            Files.delete(dir.resolve(n));
        }
        Files.delete(dir);
    }
}

How It Works

  1. Alternatives in braces. {jpg,png} means either extension, and * stands for any name before the dot.
  2. The dot is literal. A file called just jpg does not match, because the pattern requires a . before the extension.
  3. Names only. The glob is tested against the entry's file name, not the full path, so the temp location never matters.

Example 3 — Skip Empty Files with DirectoryStream.Filter

A filter can check anything, here the file size. The example also shows that a stream can be iterated only once.

Java
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class NewDirectoryStreamFilter {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("demo");
        Files.write(dir.resolve("full.txt"), new byte[3]);
        Files.write(dir.resolve("empty.txt"), new byte[0]);
        Path sub = Files.createDirectory(dir.resolve("sub"));
        DirectoryStream.Filter<Path> nonEmpty = new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path entry) throws IOException {
                return Files.isRegularFile(entry) && Files.size(entry) > 0;
            }
        };
        List<String> kept = new ArrayList<>();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, nonEmpty)) {
            for (Path entry : stream) {
                kept.add(entry.getFileName().toString());
            }
            try {
                stream.iterator();
            } catch (IllegalStateException e) {
                System.out.println("Second iterator: IllegalStateException");
            }
        }
        System.out.println("Non-empty files: " + kept);
        Files.delete(sub);
        Files.delete(dir.resolve("empty.txt"));
        Files.delete(dir.resolve("full.txt"));
        Files.delete(dir);
    }
}

How It Works

  1. Any rule you like. accept may throw IOException, so it can call Files.size directly.
  2. One match. empty.txt has size 0 and sub is a folder, so only full.txt is kept; with one name, sorting is not needed.
  3. Single use. After the for-each loop has taken the iterator, asking for another throws IllegalStateException. Open a new stream to list again.

Frequently Asked Questions

try (DirectoryStream<Path> s = Files.newDirectoryStream(dir, "*.txt")) { for (Path p : s) { ... } }.
* for any characters, ? for one character, {a,b} for alternatives, and [abc] for character sets.
No. It lists one folder. Use Files.walk or Files.walkFileTree for subfolders.
No. A second iterator() call throws IllegalStateException; open a new stream instead.
They read the same entries. Files.list returns a Java 8 Stream; newDirectoryStream works in a for-each loop and supports glob filters directly.

Next: Files.newInputStream()

Open a file as an InputStream for reading raw bytes.

newInputStream() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful