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

前端 未结 7 1463
旧时难觅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:23

    There's always just reading byte by byte from each file and comparing them as you go. Md5 and Sha1 etc still have to read all the bytes so computing the hash is extra work that you don't have to do.

    if(file1.length() != file2.length()){
            return false;
     }
    
     try(   InputStream in1 =new BufferedInputStream(new FileInputStream(file1));
        InputStream in2 =new BufferedInputStream(new FileInputStream(file2));
     ){
    
          int value1,value2;
          do{
               //since we're buffered read() isn't expensive
               value1 = in1.read();
               value2 = in2.read();
               if(value1 !=value2){
               return false;
               }
          }while(value1 >=0);
    
     //since we already checked that the file sizes are equal 
     //if we're here we reached the end of both files without a mismatch
     return true;
    }
    

提交回复
热议问题