【问题标题】:java.util.zip.ZipException: oversubscribed dynamic bit lengths treejava.util.zip.ZipException:超额订阅动态位长度树
【发布时间】:2011-03-04 05:29:53
【问题描述】:

我正在使用 gzip 压缩一个字符串,然后解压缩结果,但是我得到了以下异常,为什么?

 输出:
线程“主”java.util.zip.ZipException 中的异常:超额订阅动态位长度树
 在 java.util.zip.InflaterInputStream.read(未知来源)
 在 java.util.zip.GZIPInputStream.read(未知来源)
 在 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);
 }
}

【问题讨论】:

    标签: java gzip


    【解决方案1】:

    根据this page,可能的原因是您尝试读取的 ZIP 文件已损坏。 (我知道这与您的情况不完全匹配......但我确信异常消息是指示性的。)

    在您的情况下,问题在于您将 gzip 流从字节数组转换为字符串,然后再转换回字节数组。这几乎可以肯定是有损操作,会导致 GZIP 流损坏。

    如果要将任意字节数组转换为字符串形式并返回,则需要使用为此目的设计的字符串编码格式之一;例如base64。

    或者,只需更改以下内容:

        String out = outstream.toString();
        ByteArrayInputStream in = new ByteArrayInputStream(out.getBytes());
    

    到这里:

        byte[] out = outstream.toByteArray();
        ByteArrayInputStream in = new ByteArrayInputStream(out);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 2014-05-02
      • 2012-04-06
      • 1970-01-01
      • 2021-04-22
      • 2018-08-28
      • 1970-01-01
      相关资源
      最近更新 更多