Java 解压缩用 zlib deflate 压缩的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33020765/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 21:05:46  来源:igfitidea点击:

Java Decompress a string compressed with zlib deflate

javazlibdeflate

提问by keocra

As the title says. How do you decompress a compressed string which was compressed with zlib deflate? What is the solid way of doing it with an explanation?

正如标题所说。如何解压缩用 zlib deflate 压缩的压缩字符串?用解释做这件事的可靠方法是什么?

回答by keocra

Try this - it is a minimal working example:

试试这个 - 这是一个最小的工作示例:

package zlib.example;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;

/**
 * Created by keocra on 08.10.15.
 */
public class Main {
    private final static String inputStr = "Hello World!";

    public static void main(String[] args) throws Exception {
        System.out.println("Will zlib compress following string: " + inputStr);

        // will compress "Hello World!"
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DeflaterOutputStream dos = new DeflaterOutputStream(baos);
        dos.write(inputStr.getBytes());
        dos.flush();
        dos.close();

        // at this moment baos.toByteArray() holds the compressed data of "Hello World!"

        // will decompress compressed "Hello World!"
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        InflaterInputStream iis = new InflaterInputStream(bais);

        String result = "";
        byte[] buf = new byte[5];
        int rlen = -1;
        while ((rlen = iis.read(buf)) != -1) {
            result += new String(Arrays.copyOf(buf, rlen));
        }

        // now result will contain "Hello World!"

        System.out.println("Decompress result: " + result);
    }
}

You should also easily be able to extend this example to compress/decompress files.

您还应该能够轻松地扩展此示例以压缩/解压缩文件。

Hope it helps ;-)

希望能帮助到你 ;-)

Further readings:

进一步阅读:

回答by Saravana

I found thisarticle in Google, it explains how to compress and decompress in java using zlib, hope it helps

我在谷歌上找到这篇文章,它解释了如何使用 zlib 在 java 中压缩和解压缩,希望它有所帮助