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;
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.
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.
The more common method is to calculate the md5 equivalent for comparison
Get the hash value. Common algorithms include MD5, SHA-256
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.