Files Find Glob Matcher Depth Cap
Search a directory tree lazily with Files.find, pairing a glob PathMatcher with file attributes and a depth cap instead of walking every node.
Code
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.util.stream.Stream;
public class CsvSweep {
public static void main(String[] args) throws IOException {
Path root = Files.createTempDirectory("reports");
Path nested = root.resolve("2026").resolve("11");
Files.createDirectories(nested);
Files.writeString(root.resolve("summary.csv"), "region,orders\n");
Files.writeString(nested.resolve("daily.csv"), "day,orders\n");
Files.writeString(nested.resolve("notes.txt"), "scratch\n");
PathMatcher csv = root.getFileSystem().getPathMatcher("glob:**/*.csv");
// Files.find:深度受限的惰性递归查找,谓词同时拿到路径和属性
try (Stream<Path> hits = Files.find(root, 3,
(path, attrs) -> attrs.isRegularFile() && csv.matches(path))) {
hits.map(root::relativize).sorted().forEach(System.out::println);
}
// maxDepth = 1:只扫第一层,嵌套文件不进结果
try (Stream<Path> topOnly = Files.find(root, 1,
(path, attrs) -> attrs.isRegularFile())) {
System.out.println("depth-1 files: " + topOnly.count());
}
}
}What the code does
The working surface is the class CsvSweep — everything else is wiring.
Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.
Using it
The demo output is labeled (depth-1 files:), so every printed line maps back to its originating operation.
Key statements
PathMatcher csv = root.getFileSystem().getPathMatcher("glob:**/*.csv");
Files.writeString(root.resolve("summary.csv"), "region,orders\n");
Files.writeString(nested.resolve("daily.csv"), "day,orders\n");
Interactive Tools for This Topic
Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.URL Pattern MatcherTest Express-style URL patterns with :param and wildcard segments against concrete paths and extract the captured parameter values.
FAQ
- What does Files Find Glob Matcher Depth Cap print when run?
- Running the file directly is enough — expect labeled output lines such as `depth-1 files:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.