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

前端 未结 7 1295
旧时难觅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条回答
  • 2021-02-07 18:25

    Read the files in (small) blocks and compare them:

    static boolean binaryDiff(File a, File b) throws IOException {
        if(a.length() != b.length()){
            return false;
        }
    
        final int BLOCK_SIZE = 128;
        InputStream aStream = new FileInputStream(a);
        InputStream bStream = new FileInputStream(b);
        byte[] aBuffer = new byte[BLOCK_SIZE];
        byte[] bBuffer = new byte[BLOCK_SIZE];
        while (true) {
            int aByteCount = aStream.read(aBuffer, 0, BLOCK_SIZE);
            bStream.read(bBuffer, 0, BLOCK_SIZE);
            if (aByteCount < 0) {
                return true;
            }
            if (!Arrays.equals(aBuffer, bBuffer)) {
                return false;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题