Java:如何检查2个二进制文件是否相同?

DP_*_*DP_ 9 java

检查(在单元测试中)二进制文件A和B是否相等的最简单方法是什么?

Lou*_*man 11

第三方图书馆是公平游戏吗?番石榴有Files.equal(File, File).如果你不需要,没有真正的理由去打扰哈希; 它只会效率低下.


dka*_*zel 5

总是只是从每个文件中逐字节读取并随时比较它们.Md5和Sha1等仍然必须读取所有字节,因此计算哈希是额外的工作,你不必这样做.

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这取决于您需要比较多少次.如果你有文件A,并且你需要比较许多文件(B1,...,Bn),那么计算哈希可能更有效.这样,每次测试时都不必遍历A的整个字节.您可以将哈希值放入单元测试中并对其进行检查(如果文件发生更改,请确保更改哈希值). (3认同)