← 中文资源

简体中文版本

Files.find 按 glob 与深度查找

Files.find 拿 glob 匹配器和文件属性谓词做深度受限的惰性递归查找:maxDepth 收口扫描范围,try-with-resources 保证流及时关闭。

阅读英文原文

实现说明

活动部件是类 CsvSweep。 资源写在 try 头部,关闭由编译器生成、异常安全。

使用要点

  • 每一步打印都带着自己的标签:depth-1 files:。

常见问题

运行「Files.find 按 glob 与深度查找」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 depth-1 files: 这类标签。

核心语句

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");

代码示例

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());
        }
    }
}