如何判断两个文件内容是否相同

如何判断两个文件内容是否相同?

一、MD5判断

​ 通过MD5比对两个文件是否相等,你可以计算每个文件的MD5哈希值,然后将这些哈希值进行比较。如果两个文件的MD5哈希值相同,那么这两个文件内容也相同。

import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileMD5Comparison {
    public static void main(String[] args) {
        String file1Path = "path/to/file1";
        String file2Path = "path/to/file2";

        try {
            String md5File1 = calculateMD5(file1Path);
            String md5File2 = calculateMD5(file2Path);

            if (md5File1.equals(md5File2)) {
                System.out.println("Files are equal.");
            } else {
                System.out.println("Files are not equal.");
            }
        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    // 计算文件的MD5哈希值
    private static String calculateMD5(String filePath) throws IOException, NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        try (FileInputStream fis = new FileInputStream(filePath)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                md5.update(buffer, 0, bytesRead);
            }
        }
        byte[] digest = md5.digest();
        StringBuilder md5HexString = new StringBuilder();
        for (byte b : digest) {
            md5HexString.append(String.format("%02x", b & 0xff));
        }
        return md5HexString.toString();
    }
}

你可能感兴趣的:(java,开发语言)