1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- package com.baidu;
- import java.io.*;
- import java.nio.file.*;
- import java.security.*;
- import java.util.*;
- public class FileMD5Matcher {
- // 计算文件的 MD5 值
- public static String calculateMD5(Path path) throws Exception {
- MessageDigest md = MessageDigest.getInstance("MD5");
- try (InputStream is = Files.newInputStream(path);
- DigestInputStream dis = new DigestInputStream(is, md)) {
- byte[] buffer = new byte[8192];
- while (dis.read(buffer) != -1) {
- }
- }
- byte[] digest = md.digest();
- StringBuilder sb = new StringBuilder();
- for (byte b : digest) {
- sb.append(String.format("%02x", b));
- }
- return sb.toString();
- }
- // 构建原始目录的 MD5 -> 文件名 映射
- public static Map<String, String> buildOriginalMD5Map(String originalDir) throws Exception {
- Map<String, String> md5ToFilename = new HashMap<>();
- Files.list(Paths.get(originalDir))
- .filter(Files::isRegularFile)
- .forEach(path -> {
- try {
- String md5 = calculateMD5(path);
- md5ToFilename.put(md5, path.getFileName().toString());
- } catch (Exception e) {
- System.err.println("无法处理文件: " + path + ", 错误: " + e.getMessage());
- }
- });
- return md5ToFilename;
- }
- // 匹配新目录中的文件与原始目录中的 MD5
- public static void matchNewFilesWithOriginals(String newDir, Map<String, String> originalMD5Map) throws Exception {
- Map<String, String> matches = new HashMap<>();
- Files.list(Paths.get(newDir))
- .filter(Files::isRegularFile)
- .forEach(path -> {
- try {
- String md5 = calculateMD5(path);
- String originalName = originalMD5Map.get(md5);
- if (originalName != null) {
- matches.put(path.getFileName().toString(), originalName);
- }
- } catch (Exception e) {
- System.err.println("无法处理文件: " + path + ", 错误: " + e.getMessage());
- }
- });
- matches.forEach((newName, originalName) ->
- System.out.println(newName + " -> " + originalName));
- }
- public static void main(String[] args) {
- String originalDir = "D:\\Project\\2025\\02.成都停车项目POC\\20250606\\source";
- String newDir = "D:\\Project\\2025\\02.成都停车项目POC\\20250606\\no";
- try {
- Map<String, String> originalMD5Map = buildOriginalMD5Map(originalDir);
- matchNewFilesWithOriginals(newDir, originalMD5Map);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
|