Custom DirectoryStream.Filter Predicates
You'll learn how to create your own programmatic filters to control which directory entries appear when iterating.
While glob patterns (like "*.txt") are convenient for simple file name matching, they can't filter based on file attributes like size, modification date, or permissions. That's where custom DirectoryStream.Filter<Path> predicates come in.
What Is a DirectoryStream.Filter?
A DirectoryStream.Filter<Path> is a functional interface with a single method: accept(Path entry). You implement this method to return true for entries you want to include, and false for those you want to skip.
Think of it like a bouncer at a club—each file or directory "walks up," and your filter decides whether to let it through based on whatever criteria you choose.
Creating Custom Filters
You can implement the filter as a lambda, anonymous class, or named class:
// Filter for files larger than 1MB
DirectoryStream.Filter<Path> largeFilesFilter = path ->
Files.isRegularFile(path) && Files.size(path) > 1_000_000;
try (DirectoryStream<Path> stream =
Files.newDirectoryStream(Paths.get("/mydir"), largeFilesFilter)) {
for (Path entry : stream) {
System.out.println(entry.getFileName());
}
}
Common Use Cases
Combine file attributes for sophisticated filtering:
// Files modified in the last 7 days
DirectoryStream.Filter<Path> recentFilter = path -> {
FileTime lastMod = Files.getLastModifiedTime(path);
long age = System.currentTimeMillis() - lastMod.toMillis();
return age < 7 * 24 * 60 * 60 * 1000L;
};
// Readable directories only
DirectoryStream.Filter<Path> readableDirs = path ->
Files.isDirectory(path) && Files.isReadable(path);
Key Takeaway: Implement DirectoryStream.Filter<Path> to filter directory entries based on any file attributes or custom logic, giving you complete control beyond simple glob patterns.