实现高效的文件内容比较工具函数。
参考了网上的一些方法并做了改进。 测试发现使用MD5方式比较是不完备的,如果文件只改动一个字节,比如 本来数字“1”改成数字“2”,是无法正确比较的。
所以还是采用了读取所有字节进行比较的方式比较靠谱。读取文件内容是的buffer大小会影响执行效率。对于10K级别的文本文件,经测试在10MS以内比较完成。
/**
* <p>
* compare two file's content. if not equal then return false; else return true;
* </p>
* @param oldFilePath
* @param newFilePath
* @return
*/
public static boolean isFileContentEqual(String oldFilePath, String newFilePath) {
//check does the two file exist.
if (!TextUtils.isEmpty(oldFilePath) && !TextUtils.isEmpty(newFilePath)) {
File oldFile = new File(oldFilePath);
File newFile = new File(newFilePath);
FileInputStream oldInStream = null;
FileInputStream newInStream = null;
try {
oldInStream = new FileInputStream(oldFile);
newInStream = new FileInputStream(newFile);
int oldStreamLen = oldInStream.available();
int newStreamLen = newInStream.available();
//check the file size first.
if (oldStreamLen > 0 && oldStreamLen == newStreamLen) {
//read file data with a buffer.
int cacheSize = 128;
byte[] data1 = new byte[cacheSize];
byte[] data2 = new byte[cacheSize];
do {
int readSize = oldInStream.read(data1);
newInStream.read(data2);
for (int i = 0; i < cacheSize; i++) {
if (data1[i] != data2[i]) {
return false;
}
}
if (readSize == -1) {
break;
}
} while (true);
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//release the stream resource.
try {
if (oldInStream != null)
oldInStream.close();
if (newInStream != null)
newInStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return false;
}
参考了文章:java比较文件内容是否相同的方法