Files Walk Directory Tree Sizing
Traverse a directory tree with Files.walk inside try-with-resources, filter by extension, and aggregate per-extension file counts and sizes.
Code
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;
}
}
}How it works
The snippet is organized around the classes TreeSizeReport and Stats and the function extensionOf.
The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable. Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.
Putting it to use
The primary signature is private static String extensionOf(Path p)
The entry point wires extensionOf together — run it once and the whole demo flows.
Core lines
.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);
FAQ
- How do you run Files Walk Directory Tree Sizing?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.