-4

设想:

  1. 一个标准交易文件(csv)将在那里(file1.csv)
  2. 其他文件(file2.csv)假设它是其他模块的输出,

任务:file1 和 file2 应该匹配(标题和数据)都应该匹配,

4

1 回答 1

0

您可以使用哈希检查文件是否相等。

如果两个文件的哈希值匹配,则文件完全相同。

最常见的散列技术是 MD5 和 SHA1。它适用于最常见的目的。(除非您将它们用于加密或安全目的!)

您的 JRE 附带java.security.MessageDigest提供散列的类。

这是您可以使用的示例代码:

public class HashCheck {

    public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
        byte[] file1Contents = Files.readAllBytes(Paths.get("C:/path/to/file1.csv"));
        byte[] file2Contents = Files.readAllBytes(Paths.get("C:/path/to/file2.csv"));

        String hashtext1 = computeHash(file1Contents);
        String hashtext2 = computeHash(file2Contents);
        System.out.println(hashtext1);
        System.out.println(hashtext2);
        System.out.println(hashtext1.equals(hashtext2));
    }

    public static String computeHash(String input) throws NoSuchAlgorithmException {
        return computeHash(input.getBytes());
    }

    public static String computeHash(byte[] input) throws NoSuchAlgorithmException {
        MessageDigest hasher = java.security.MessageDigest.getInstance("MD5"); //MD5 or SHA1
        hasher.reset();
        hasher.update(input);
        byte[] digest = hasher.digest();
        BigInteger bigInt = new BigInteger(1, digest);
        String hashtext = bigInt.toString(16); // The hashes are base-16 numbers
        // Now we need to zero pad it if you actually want the full 32 chars.
        while(hashtext.length() < hasher.getDigestLength() ){
          hashtext = "0"+hashtext;   
        }
        return hashtext;
    }

}

希望这可以帮助!

于 2017-03-16T10:32:53.193 回答