Java 解压缩用 zlib deflate 压缩的字符串 [英] Java Decompress a string compressed with zlib deflate

查看:57
本文介绍了Java 解压缩用 zlib deflate 压缩的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说.如何解压缩用 zlib deflate 压缩的压缩字符串?有解释的可靠方法是什么?

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?

推荐答案

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

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.

希望它有帮助;-)

进一步阅读:

这篇关于Java 解压缩用 zlib deflate 压缩的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆