获取并加载文件之后,通过计算并比较两个问件的MD5值,以比较两个文件的内容是否相同。
public class TestCompareFileContent{
public static void main(String[] args){
String pathFirst="D:\\a.txt";
String pathSecond="D:\\b.txt";
File fileFirst=new File(pathFirst);
File fileSecond=new File(pathSecond);
String firstMD5=getFileMD5(fileFirst);
String secondMD5=getFileMD5(fileSecond);
System.out.println(firstMD5.equals(secondMD5));
}
public static String getFileMD5(File file){
if (!file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte[8192];
int len;
try {
digest =MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer)) != -1) {
digest.update(buffer, 0, len);
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}