实现说明
真正干活的是类 DuplicateFinder和函数 fingerprint,其余都是接线。
stream 各阶段从左到右组合——终端操作执行之前什么都不会跑。资源写在 try 头部,关闭由编译器生成、异常安全。UncheckedIOException、IllegalStateException 是守卫的信号——在分支处抛出,任何半成品工作之前。
使用要点
- 每一步打印都带着自己的标签:
duplicates:。 main按顺序串起fingerprint;运行文件就会把这个流程跑一遍。
常见问题
这段代码会校验输入吗?
在真正开工之前就会抛出 UncheckedIOException、IllegalStateException——请在调用点处理,或有意向上传播。
运行「按大小与哈希查找重复文件」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 duplicates: 这类标签。
主要签名是 static String fingerprint(Path path)
核心语句
.collect(Collectors.groupingBy(DuplicateFinder::fingerprint));
.map(group -> group.stream().sorted().toList())
.forEach(group -> System.out.println("duplicates: " + group));
return Files.size(path) + ":" + HexFormat.of().formatHex(hash);
代码示例
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class DuplicateFinder {
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("dups-");
Files.writeString(dir.resolve("a.txt"), "same bytes");
Files.writeString(dir.resolve("b.txt"), "same bytes");
Files.writeString(dir.resolve("c.txt"), "different bytes");
try (Stream<Path> paths = Files.walk(dir)) {
Map<String, List<Path>> groups = paths
.filter(Files::isRegularFile)
.collect(Collectors.groupingBy(DuplicateFinder::fingerprint));
groups.values().stream()
.filter(group -> group.size() > 1)
.map(group -> group.stream().sorted().toList())
.forEach(group -> System.out.println("duplicates: " + group));
}
}
// file size gates the cheap path; the SHA-256 hash confirms byte equality
static String fingerprint(Path path) {
try {
byte[] hash = MessageDigest.getInstance("SHA-256")
.digest(Files.readAllBytes(path));
return Files.size(path) + ":" + HexFormat.of().formatHex(hash);
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}