您的位置:首页 > 其它

Unexpected end of ZLIB input stream的解决办法

2017-01-17 10:07 447 查看
在JDK1.6下使用Zip解压会出现Unexpected end of ZLIB input stream错误提示,在jdk1.7下一切正常,在官方也明确指出这是一个BUG,并在1.7中修复

应该反复比对两种版本下的区别发现问题了的根源,下面先看使用zip解压的一段代码:

String result = "";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ByteArrayInputStream bis = null;
ZipInputStream zis = null;
try {
//bytes 是传入需要解压的字节数组
bis = new ByteArrayInputStream(bytes);
zis = new ZipInputStream(bis);
ZipEntry entry = zis.getNextEntry();

byte[] buf = new byte[2048];
int offset = -1;

while((offset = zis.read(buf)) != -1) {
bos.write(buf, 0, offset);
}
result = bos.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(zis != null) {
try {zis.close();} catch(IOException e) {}
}
if(bis != null) {
try {bis.close();} catch(IOException e) {}
}
try {bos.close();} catch(IOException e) {}
}


上述代码在JDK1.6下会抛出异常,主要原因是最后一次空读引起,也就是最后一次read操作返回-1时,在JDK1.6下会偶尔出现类似的现象,官方指出是类似折行”nowarp”引起的问题,只要避免最后一次空读就不会抛出上述的异常,异常块中改为 result = bos.toString(); 即可,或者如下:

while(true) {
int offset = -1;
try{offset = zis.read(buf);}catch(EOFException ex){}
if(offset!=-1){
bos.write(buf, 0, offset);
}else{
break;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: