Filtering Directory Entries with Glob Patterns
You'll learn how to apply glob patterns when creating directory streams to automatically filter which entries are returned.
The Core Idea
Instead of reading all directory entries and then filtering them in your code, you can pass a glob pattern directly to Files.newDirectoryStream() at creation time. The pattern acts like a doorman that only lets matching files through—non-matching entries never even reach your loop.
Glob patterns are simple wildcard expressions:
*matches any sequence of characters within a name (but not directory separators)**matches across directory boundaries?matches a single character{txt,java}matches either "txt" or "java"
Think of glob filtering as setting criteria at the source—like telling a librarian "only bring me books about Java" rather than having them bring you every book and sorting through them yourself.
Common Glob Examples
// Only .txt files
DirectoryStream<Path> txtFiles =
Files.newDirectoryStream(dir, "*.txt");
// Only .java files
DirectoryStream<Path> javaFiles =
Files.newDirectoryStream(dir, "*.java");
// Files starting with "test"
DirectoryStream<Path> testFiles =
Files.newDirectoryStream(dir, "test*");
// Multiple extensions
DirectoryStream<Path> codeFiles =
Files.newDirectoryStream(dir, "*.{java,class}");
The filtering happens at the filesystem level, making it more efficient than retrieving everything and filtering manually. The resulting DirectoryStream only yields paths that match your pattern.
Key Takeaway: Glob patterns in Files.newDirectoryStream() filter directory entries at creation time using wildcards like *.txt or **.java, providing an efficient way to process only files matching specific criteria without manual filtering loops.