如果文件用字节从头至尾的比较方式,对于大文件的比较会非常的慢
我写了下面的代码,对于两个文件比较好像还没什么问题,但是要比较某一压缩包中的文件与外面一个文件是否一致时出现问题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个字节
我写了下面的代码,对于两个文件比较好像还没什么问题,但是要比较某一压缩包中的文件与外面一个文件是否一致时出现问题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个字节
InputStream ois=null;
try {
byte[] srcBuff = new byte[8192];
byte[] descBuff = new byte[8192];
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;
} for(int i=0;i<descLen;i++) {
if(srcBuff[i]!=descBuff[i]) {
return false;
}
}
}
} catch (Exception e) {
return false;
}finally {
if(ois!=null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}