← 中文资源

简体中文版本

Files.walk 目录树统计

用 Files.walk 在 try-with-resources 中遍历目录树,按扩展名聚合文件数与字节数,输出前五大类型。

阅读英文原文

实现说明

底层就是类 TreeSizeReport、Stats和函数 extensionOf。 转换写成 stream 链,由收集器一次性执行。try-with-resources 会在每条退出路径上自动关闭声明的资源。

使用要点

  • main 按顺序串起 extensionOf;运行文件就会把这个流程跑一遍。

常见问题

「Files.walk 目录树统计」这个示例怎么运行?

把它当完整程序编译/解释运行即可——不需要先安装任何东西。

入口签名:private static String extensionOf(Path p)

核心语句

.collect(Collectors.toMap(
        TreeSizeReport::extensionOf,
        p -> {
            try {
                long size = Files.size(p);
                return new Stats(1, size);
            } catch (IOException e) {
                return new Stats(1, 0);
            }
        },
        Stats::plus));
return dot < 0 ? "(none)" : name.substring(dot + 1).toLowerCase();
return new Stats(count + other.count, bytes + other.bytes);

代码示例

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TreeSizeReport {

    public static void main(String[] args) throws IOException {
        Path root = Path.of(args.length > 0 ? args[0] : ".");

        // Stream 必须关闭:底层持有目录句柄
        try (Stream<Path> paths = Files.walk(root)) {
            Map<String, Stats> byExtension = paths
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toMap(
                            TreeSizeReport::extensionOf,
                            p -> {
                                try {
                                    long size = Files.size(p);
                                    return new Stats(1, size);
                                } catch (IOException e) {
                                    return new Stats(1, 0);
                                }
                            },
                            Stats::plus));

            byExtension.entrySet().stream()
                    .sorted(Map.Entry.<String, Stats>comparingByValue(
                            (a, b) -> Long.compare(b.totalBytes(), a.totalBytes())))
                    .limit(5)
                    .forEach(e -> System.out.printf("%-8s %6d files %12d bytes%n",
                            e.getKey(), e.getValue().count(), e.getValue().totalBytes()));
        }
    }

    private static String extensionOf(Path p) {
        String name = p.getFileName().toString();
        int dot = name.lastIndexOf('.');
        return dot < 0 ? "(none)" : name.substring(dot + 1).toLowerCase();
    }

    record Stats(long count, long bytes) {
        Stats plus(Stats other) {
            return new Stats(count + other.count, bytes + other.bytes);
        }
        long totalBytes() {
            return bytes;
        }
    }
}