比较两个文件是否相同,一般都是比较文件的MD5值是否相同,java中计算MD5值的方法如下:
private MessageDigest mMessageDigest = null;
try {
mMessageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
* obtain the file's MD5
*/
public String getFileMD5String(File file) {
try {
InputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int length = -1;
while ((length = fis.read(buffer, 0, 1024)) > 0) {
mMessageDigest.update(buffer, 0, length);
}
fis.close();
return new BigInteger(1, mMessageDigest.digest()).toString(16);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private boolean isSmaeFile(String filePath1, String filePath2) {
boolean result = true;
File file1 = new File(filePath1);
File file2 = new File (filePath2);
if (externalFile.length() != internallFile.length()) {
result = false;
break;
} else {
String file1MD5 = getFileMD5String(file1);
String file2MD5 = getFileMD5String(file2);
if (file1MD5 != null && !file1MD5.equals(file2MD5)) {
result = false;
break;
}
}
return result;
}