我正在使用gzip压缩字符串,然后解压缩结果,但是我得到以下异常,为什么?
output: Exception in thread "main" java.util.zip.ZipException: oversubscribed dynamic bit lengths tree at java.util.zip.InflaterInputStream.read(Unknown Source) at java.util.zip.GZIPInputStream.read(Unknown Source) at Test.main(Test.java:25)
public class Test {
public static void main(String[]args) throws IOException{
String s="helloworldthisisatestandtestonlydsafsdafdsfdsafadsfdsfsdfdsfdsfdsfdsfsadfdsfdasfassdfdfdsfdsdssdfdsfdsfd";
byte[]bs=s.getBytes();
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
GZIPOutputStream gzipOut = new GZIPOutputStream(outstream);
gzipOut.write(bs);
gzipOut.finish();
String out=outstream.toString();
System.out.println(out);
System.out.println(out.length());
ByteArrayInputStream in = new ByteArrayInputStream(out.getBytes());
GZIPInputStream gzipIn=new GZIPInputStream(in);
byte[]uncompressed = new byte[100000];
int len=10, offset=0, totalLen=0;
while((len = gzipIn.read(uncompressed, offset, len)) >0){ // this line
offset+=len;
totalLen+=len;
}
String uncompressedString=new String(uncompressed,0,totalLen);
System.out.println(uncompressedString);
}
}
答案 0 :(得分:8)
根据this page,可能的原因是您尝试阅读的ZIP文件已损坏。 (我知道这与你的情况并不完全匹配......但我确信异常消息是指示性的。)
在您的情况下,问题是您正在将gzip流从字节数组转换为String,然后再转换回字节数组。这几乎肯定是一个有损操作,导致GZIP流损坏。
如果要将任意字节数组转换为字符串形式并返回,则需要使用为此目的设计的字符串编码格式之一;例如BASE64。
或者,只需更改此内容:
String out = outstream.toString();
ByteArrayInputStream in = new ByteArrayInputStream(out.getBytes());
到此:
byte[] out = outstream.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(out);