java 15 lines · 5 steps

Expanding glob patterns with NIO

Turn a glob string into a sorted list of matching paths by walking a directory tree and testing each entry.

Explained by highlit
1public List<Path> expandGlob(Path baseDir, String glob) throws IOException {
2 FileSystem fs = baseDir.getFileSystem();
3 PathMatcher matcher = fs.getPathMatcher("glob:" + glob);
4 boolean recursive = glob.contains("**");
5 int maxDepth = recursive ? Integer.MAX_VALUE : 1;
6 
7 List<Path> matches = new ArrayList<>();
8 try (Stream<Path> paths = Files.walk(baseDir, maxDepth)) {
9 paths.filter(path -> !path.equals(baseDir))
10 .filter(path -> matcher.matches(baseDir.relativize(path)))
11 .sorted()
12 .forEach(matches::add);
13 }
14 return matches;
15}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A PathMatcher lets you reuse compiled glob logic instead of hand-rolling wildcard parsing.
  2. 2Matching relative paths keeps glob semantics independent of the absolute location of the base directory.
  3. 3Streams from Files.walk hold OS resources, so closing them in try-with-resources prevents descriptor leaks.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Expanding glob patterns with NIO — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code