java 文件内容_JAVA高效文件内容比较

实现高效的文件内容比较工具函数。

参考了网上的一些方法并做了改进。 测试发现使用MD5方式比较是不完备的,如果文件只改动一个字节,比如 本来数字“1”改成数字“2”,是无法正确比较的。

所以还是采用了读取所有字节进行比较的方式比较靠谱。读取文件内容是的buffer大小会影响执行效率。对于10K级别的文本文件,经测试在10MS以内比较完成。

/**

*

* compare two file's content. if not equal then return false; else return true;

*

* @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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值