【问题标题】:GZIP compression and decompressionGZIP压缩和解压
【发布时间】:2014-04-07 18:49:11
【问题描述】:

我正在使用以下代码压缩然后解压缩字符串。但是我在解压后得到了不同长度的字符串,解压后的字符串中也缺少几个字符。

压缩:

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            GZIPOutputStream zos = new GZIPOutputStream(baos);

            zos.write(text.getBytes());
            zos.finish();
            zos.flush();

            byte[] udpBuffer = baos.toByteArray();          
            System.out.println("Compressed length: " + udpBuffer.length);

解压:

        GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
        BufferedReader br = new BufferedReader(new InputStreamReader(gis));     

        StringBuilder sb = new StringBuilder();
        while (br.readLine()!= null) {
            sb.append(br.readLine());
        }

        System.err.println(sb.toString());

文本原始长度:45627 字节
文本压缩长度:3732 字节
文本未压缩长度:20328 字节(应等于原始长度)

我的原文是这样的:

<html>
<head>
   <title></title>
</head>
<body>
<p><span class="preheader" style="display:none!important;mso-hide:all">Hey wazzup? </span></p>

<table align="center" border="0" cellpadding="0" cellspacing="0" width="640">
   <tbody>
       <tr>
           <td align="center" height="30" style="font-size:11px;color:#333;font-family:Verdana,Geneva,sans-serif">
.
.
.
</tbody>
</body>
</html>

而我的解压文本来了(见缺少开始标签,还有

<title> tag, similarly many tags and other parts are missing from my uncompressed text:
<head></head><p><span class="preheader" style="display:none!important;mso-hide:all">
.
.
.

谁能指出错误?或者这是预期的行为?

【问题讨论】:

    标签: java compression gzip gzipinputstream


    【解决方案1】:

    改变

    while (br.readLine()!= null) {
        sb.append(br.readLine());
    }
    

    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    

    另外,zos.flush() 应该在 zos.finish() 之前调用。

    【讨论】:

    • 它成功了!谢谢!但是第一个版本的 while 有什么问题呢?
    • "while (br.readLine()!=null)" 读取一行并检查该行是否等于 null。 "sb.append(br.readLine())" 读取 NEXT 行并将其附加到 StringBuilder。在“while (br.readLine()!=null)”中读取的行被简单地丢弃而不被附加到 StringBuilder。
    猜你喜欢
    • 2012-09-25
    • 2012-02-12
    • 2023-03-18
    • 2015-07-14
    • 2015-02-06
    • 2021-11-30
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多