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.
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
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);
}
}
Output
Run with java NewDirectoryStreamLoop. Directory order is unspecified, so the program sorts the names before printing; the output is the same on Windows, macOS, and Linux.
[a.txt, b.txt, pics/]
How It Works
An Iterable.DirectoryStream works directly in a for-each loop, which is why it fits Java 7 code without streams.
Label folders.Files.isDirectory(entry) adds a slash to pics so it stands out.
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);
}
}
Output
Run with java NewDirectoryStreamGlob. Directory order is unspecified, so the program sorts the names before printing; the output is the same on Windows, macOS, and Linux.
Images: [cat.jpg, dog.png]
How It Works
Alternatives in braces.{jpg,png} means either extension, and * stands for any name before the dot.
The dot is literal. A file called just jpg does not match, because the pattern requires a . before the extension.
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);
}
}
Output
Run with java NewDirectoryStreamFilter. The output is the same on Windows, macOS, and Linux.
Second iterator: IllegalStateException
Non-empty files: [full.txt]
How It Works
Any rule you like.accept may throw IOException, so it can call Files.size directly.
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.
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.