Creating DirectoryStreams with Files.newDirectoryStream
You'll learn how to obtain an iterable stream over directory contents using Files.newDirectoryStream with proper resource management.
What Is newDirectoryStream?
The Files.newDirectoryStream(Path) method returns a DirectoryStream<Path> that lets you iterate over entries in a directory. Think of it like opening a book to read its table of contents—you get access to see what's inside, but you need to close the book when you're done.
Creating a DirectoryStream
Since DirectoryStream implements AutoCloseable, you should always use try-with-resources to ensure proper cleanup:
Path dir = Paths.get("myFolder");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path entry : stream) {
System.out.println(entry.getFileName());
}
} catch (IOException e) {
System.err.println("Error reading directory: " + e.getMessage());
}
Why Try-With-Resources Is Critical
Directory streams hold system resources (like file handles). If you forget to close them, you can exhaust available resources, especially when processing many directories. Try-with-resources guarantees cleanup even if exceptions occur during iteration.
Behavior Notes
- Returns entries in no specific order (not sorted)
- Does not recursively traverse subdirectories
- Includes both files and subdirectories as
Pathobjects - Special entries
.and..are not included
try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("."))) {
for (Path entry : stream) {
if (Files.isDirectory(entry)) {
System.out.println("[DIR] " + entry.getFileName());
} else {
System.out.println("[FILE] " + entry.getFileName());
}
}
} catch (IOException e) {
e.printStackTrace();
}
Key Takeaway: Use Files.newDirectoryStream(Path) with try-with-resources to safely iterate over directory contents, ensuring system resources are properly released after use.