Java Files.list and newDirectoryStream
Enumerate the immediate children of a directory and close the resulting stream.
A simple example
Files.list and newDirectoryStream
- Start with One folder containing a.txt and b.txt
- Do this List and sort its names
- Result a.txt, b.txt
Syntax
public static Stream<Path> list(Path dir) throws IOException
JDK 21 declarations (4)
public static Stream<Path> list(Path dir) throws IOExceptionpublic static DirectoryStream<Path> newDirectoryStream(Path dir) throws IOExceptionpublic static DirectoryStream<Path> newDirectoryStream(Path dir, String glob) throws IOExceptionpublic static DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) throws IOException
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCount the reading lists available for a class
A class folder contains two text reading lists and one image. The teacher wants a count of all entries as well as an alphabetical display containing only the reading lists.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Files.createFile(desk.resolve("poems.txt"));
Files.createFile(desk.resolve("map.png"));
Files.createFile(desk.resolve("essays.txt"));
try (var entries = Files.list(desk)) { System.out.println(entries.count()); }
try (var text = Files.newDirectoryStream(desk, "*.txt")) {
var names = new java.util.ArrayList<String>();
for (Path p : text) names.add(p.getFileName().toString());
names.sort(null);
System.out.println(names);
}
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
3 [essays.txt, poems.txt]
The directory stream applies the glob to each entry. Sorting makes the result independent of filesystem order.
Recognize a folder without matching invoices
A new market stall has an instruction note in its export folder but no invoices yet. Ask for CSV entries only and verify that a successful empty result is possible.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Files.createFile(desk.resolve("instructions.txt"));
try (var bills = Files.newDirectoryStream(desk, "*.csv")) {
System.out.println(bills.iterator().hasNext());
}
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
false
The listing succeeds and provides no matching entries.
Inventory class submissions
A teacher receives two top-level files and one file in a team folder. Count regular files in the top-level folder only. Do not count subfolders as files.
What to watch for
Directory iteration order is unspecified. Sort entries when output needs to be reproducible.