如何高效的比较两文件是否一样的,特别是如何比较ZIP包中某文件与外部某一文件是否一致

Yanbin_Q Yanbin_Q 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
如果文件用字节从头至尾的比较方式,对于大文件的比较会非常的慢
我写了下面的代码,对于两个文件比较好像还没什么问题,但是要比较某一压缩包中的文件与外面一个文件是否一致时出现问题

public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("c:\\test.zip");
// System.out.println(isSameFile(fis,"c:\\test.zip"));

ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze = zis.getNextEntry();
System.out.println(isSameFile(zis,"c:\\test.jpg"));
}


public static boolean isSameFile(InputStream nis,String filePath) {
try {
byte[] srcBuff = new byte[8192];
byte[] descBuff = new byte[8192];

InputStream ois = new FileInputStream(filePath);
int srcLen=-1;
int descLen=-1;

while(((srcLen=nis.read(srcBuff))!=-1) && ((descLen=ois.read(descBuff))!=-1)) {
if(srcLen!=descLen) {
return false;
}

if(!new String(srcBuff,0,srcLen).equals(new String(descBuff,0,descLen))) {
return false;
}
}
ois.close();
} catch (Exception e) {
return false;
}
return true;
}

问题在于对于一个ZipInputStream zis;
已知它的数据字节数是33.3K
设定读取缓冲buff[8192]
但是对于第一次使用
int len = zis.read(buff);
返回的len却是586,以后每次都是500左右,为什么不填弃满8192呢

直接读取文件流FileInputStream就没问题,只要剩余字节足8192,
每次读取就会填充8192个字节
...全文
评论 10
收藏 已收藏
分享
返回顶部
Yanbin_Q
Java SE 62,621 成员 307,251 内容