我想将我的输入csv文件与标准(模板)csv文件进行比较。这样,列标题也应与数据进行比较

时间:2017-03-16 09:59:30

标签: java csv filecompare

情形:

  1. std事务文件(csv)将在那里(file1.csv)
  2. 其他文件(file2.csv)假定其来自其他模块的输出
  3. 任务:file1& file2应该匹配(标题和数据)两者都应该匹配,

1 个答案:

答案 0 :(得分:0)

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

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

最常见的散列技术是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;
    }

}

希望这有帮助!