java.util.zip.ZipException:超额订阅的动态位长树
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3049448/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.util.zip.ZipException: oversubscribed dynamic bit lengths tree
提问by Stephen C
I am compressing a string using gzip, then uncompress the result, however I got the following exception, why?
我正在使用 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);
 }
}
回答by Stephen C
According to this page, a likely cause is that the ZIP file you are trying to read is corrupted. (I know it is not an exact match to your circumstances ... but I'm sure that the exception message is indicative.)
根据此页面,可能的原因是您尝试读取的 ZIP 文件已损坏。(我知道这与您的情况不完全匹配……但我确信异常消息是指示性的。)
In your case, the problem is that you are converting the gzip stream from a byte array into a String and then back to a byte array. This is almost certainly a lossy operation, resulting a corrupted GZIP stream.
在您的情况下,问题在于您将 gzip 流从字节数组转换为字符串,然后再转换回字节数组。这几乎可以肯定是有损操作,导致 GZIP 流损坏。
If you want to convert an arbitrary byte array to a string form and back, you will need to use one of the string encoding formats designed for that purpose; e.g. base64.
如果要将任意字节数组转换为字符串形式并返回,则需要使用为此目的设计的一种字符串编码格式;例如base64。
Alternatively, just change this:
或者,只需更改此:
    String out = outstream.toString();
    ByteArrayInputStream in = new ByteArrayInputStream(out.getBytes());
to this:
对此:
    byte[] out = outstream.toByteArray();
    ByteArrayInputStream in = new ByteArrayInputStream(out);

