Files.list: Stream-Based Directory Listing
What you'll learn: You'll discover how to list directory contents using a modern, functional Stream<Path> approach with Files.list().
The Core Idea
While DirectoryStream works well for traditional iteration, Files.list() provides a more modern alternative by returning a Stream<Path> of all direct children in a directory. This lets you leverage the full power of Java's Stream API—filtering, mapping, sorting, and collecting—to process directory entries functionally.
Think of it this way: DirectoryStream is like manually inspecting each item in a folder, whereas Files.list() hands you a conveyor belt of items that you can process with an assembly line of operations.
How It Works
Path dir = Paths.get("myFolder");
try (Stream<Path> stream = Files.list(dir)) {
stream.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
The stream contains only direct children—no recursive traversal. Like DirectoryStream, it's a resource that must be closed, so use try-with-resources.
Functional-Style Operations
The real power comes from Stream operations:
// Find all .txt files
try (Stream<Path> stream = Files.list(dir)) {
List<Path> textFiles = stream
.filter(p -> p.toString().endsWith(".txt"))
.collect(Collectors.toList());
}
// Count directories
try (Stream<Path> stream = Files.list(dir)) {
long dirCount = stream
.filter(Files::isDirectory)
.count();
}
You can chain filter(), map(), sorted(), and terminal operations like forEach(), count(), or collect() to process entries elegantly.
Key Differences from DirectoryStream
- Returns a
Stream<Path>instead of anIterable<Path> - Enables functional-style processing
- Must still be closed (use try-with-resources)
- Lists only direct children, not recursive
Key Takeaway: Files.list() provides a modern Stream-based approach to directory listing, enabling concise functional-style filtering, mapping, and collection of directory entries.