FileMD5Matcher.java 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package com.baidu;
  2. import java.io.*;
  3. import java.nio.file.*;
  4. import java.security.*;
  5. import java.util.*;
  6. public class FileMD5Matcher {
  7. // 计算文件的 MD5 值
  8. public static String calculateMD5(Path path) throws Exception {
  9. MessageDigest md = MessageDigest.getInstance("MD5");
  10. try (InputStream is = Files.newInputStream(path);
  11. DigestInputStream dis = new DigestInputStream(is, md)) {
  12. byte[] buffer = new byte[8192];
  13. while (dis.read(buffer) != -1) {
  14. }
  15. }
  16. byte[] digest = md.digest();
  17. StringBuilder sb = new StringBuilder();
  18. for (byte b : digest) {
  19. sb.append(String.format("%02x", b));
  20. }
  21. return sb.toString();
  22. }
  23. // 构建原始目录的 MD5 -> 文件名 映射
  24. public static Map<String, String> buildOriginalMD5Map(String originalDir) throws Exception {
  25. Map<String, String> md5ToFilename = new HashMap<>();
  26. Files.list(Paths.get(originalDir))
  27. .filter(Files::isRegularFile)
  28. .forEach(path -> {
  29. try {
  30. String md5 = calculateMD5(path);
  31. md5ToFilename.put(md5, path.getFileName().toString());
  32. } catch (Exception e) {
  33. System.err.println("无法处理文件: " + path + ", 错误: " + e.getMessage());
  34. }
  35. });
  36. return md5ToFilename;
  37. }
  38. // 匹配新目录中的文件与原始目录中的 MD5
  39. public static void matchNewFilesWithOriginals(String newDir, Map<String, String> originalMD5Map) throws Exception {
  40. Map<String, String> matches = new HashMap<>();
  41. Files.list(Paths.get(newDir))
  42. .filter(Files::isRegularFile)
  43. .forEach(path -> {
  44. try {
  45. String md5 = calculateMD5(path);
  46. String originalName = originalMD5Map.get(md5);
  47. if (originalName != null) {
  48. matches.put(path.getFileName().toString(), originalName);
  49. }
  50. } catch (Exception e) {
  51. System.err.println("无法处理文件: " + path + ", 错误: " + e.getMessage());
  52. }
  53. });
  54. matches.forEach((newName, originalName) ->
  55. System.out.println(newName + " -> " + originalName));
  56. }
  57. public static void main(String[] args) {
  58. String originalDir = "D:\\Project\\2025\\02.成都停车项目POC\\20250606\\source";
  59. String newDir = "D:\\Project\\2025\\02.成都停车项目POC\\20250606\\no";
  60. try {
  61. Map<String, String> originalMD5Map = buildOriginalMD5Map(originalDir);
  62. matchNewFilesWithOriginals(newDir, originalMD5Map);
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. }