Java: How to check that 2 binary files are same?

前端 未结 7 1459
旧时难觅i
旧时难觅i 2021-02-07 17:27

What is the easiest way to check (in a unit test) whether binary files A and B are equal?

7条回答
  •  萌比男神i
    2021-02-07 18:09

    I had to do the same in a unit test too, so I used SHA1 hashes to do that, to spare the the calculation of the hashes I check if the files sizes are equal first. Here was my attempt:

    public class SHA1Compare {
        private static final int CHUNK_SIZE = 4096;
    
        public void assertEqualsSHA1(String expectedPath, String actualPath) throws IOException, NoSuchAlgorithmException {
            File expectedFile = new File(expectedPath);
            File actualFile = new File(actualPath);
            Assert.assertEquals(expectedFile.length(), actualFile.length());
            try (FileInputStream fisExpected = new FileInputStream(actualFile);
                    FileInputStream fisActual = new FileInputStream(expectedFile)) {
                Assert.assertEquals(makeMessageDigest(fisExpected), 
                        makeMessageDigest(fisActual));
            }
        }
    
        public String makeMessageDigest(InputStream is) throws NoSuchAlgorithmException, IOException {
            byte[] data = new byte[CHUNK_SIZE];
            MessageDigest md = MessageDigest.getInstance("SHA1");
            int bytesRead = 0;
            while(-1 != (bytesRead = is.read(data, 0, CHUNK_SIZE))) {
                md.update(data, 0, bytesRead);
            }
            return toHexString(md.digest());
        }
    
        private String toHexString(byte[] digest) {
            StringBuilder sha1HexString = new StringBuilder();
            for(int i = 0; i < digest.length; i++) {
                sha1HexString.append(String.format("%1$02x", Byte.valueOf(digest[i])));
            }
            return sha1HexString.toString();
        }
    }
    

提交回复
热议问题