如何用Java判断两个文件内容是否相同?
伊谢尔伦
伊谢尔伦 2017-04-18 09:50:43
0
4
487

有两个任意格式的文件。

如何用Java判断两个文件是否一样?
或者内容是一样的(不考虑文件名等信息)。

需要考虑文件比较大的情况下的效率问题。

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all (4)
PHPzhong

If you maintain these file lists and compare them from time to time later, that meansmake surethat a file has the opportunity to be compared multiple times. The MD5 of these files can be calculated and cached, and then directly compared using MD5 later.
If you only randomly select two files for comparison temporarily, you can compare the file sizes first. If the file sizes are different, it means that the file contents are different. If the sizes are equal, you can open the input streams of the two files and compare the bytes one by one. If there are unequal bytes in the middle, it means that the two files are not equal, and then exit the comparison directly. It should be noted that the file stream must be buffered(BufferedInputStream).The reason why MD5 is not recommended is because MD5 also needs to calculate the hash value based on the entire content of the
file. However, in fact, if one byte is different halfway, it can be determined that the two files are different. There is no need to read it. The entire contents of the file.

//in1, in2为两个文件的输入流,最后注意流的关闭 int c; while ((c = in1.read()) != -1) { if (in2.read() != c) return false; } return true;
    Peter_Zhu

    The more common method is to calculate the md5 equivalent for comparison

      PHPzhong

      Get the hash value. Common algorithms include MD5, SHA-256

        PHPzhong

        First make a rough judgment based on the size and suffix of the file. If they are the same, use the MD5 value to determine whether the content is the same. The algorithm can ask Du Niang.

          Latest Downloads
          More>
          Web Effects
          Website Source Code
          Website Materials
          Front End Template
          About us Disclaimer Sitemap
          php.cn:Public welfare online PHP training,Help PHP learners grow quickly!