简体   繁体   English

如何使用 Java 代码 GZip 解压缩压缩的 String 数据

[英]How to GZip decompress a compressed String data with Java code

I have some code to uncompress gzip a compressedString as below:我有一些代码可以解压缩 gzip 压缩字符串,如下所示:

public static String decompress(String compressedString) throws IOException {
        byte[] byteCompressed = compressedString.getBytes(StandardCharsets.UTF_8)
        final StringBuilder outStr = new StringBuilder();
        if ((byteCompressed == null) || (byteCompressed.length == 0)) {
            return "";
        }
        if (isCompressed(byteCompressed)) {
            final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(byteCompressed));
            final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                outStr.append(line);
            }
        } else {
            outStr.append(byteCompressed);
        }
        return outStr.toString();
    }
public static boolean isCompressed(final byte[] compressed) {
        return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
    }

I use this code to uncompress a String as below: H4sIAAAAAAAAAHNJLQtJLS4BALwLiloHAAAA我使用此代码解压缩字符串如下:H4sIAAAAAAAAAAHNJLQtJLS4BALwLiloHAAAA

But this code uncompress a unexpected String although I can uncompress online normally in the web但是这段代码解压缩了一个意外的字符串,虽然我可以在网络上正常在线解压缩在此处输入图片说明

Anyone can help me give the right uncompress code?任何人都可以帮我提供正确的解压缩代码吗? Thanks谢谢

Your string is base64 encoded gzip data, so you need to base64 decode it, instead of trying to encode it as UTF-8 bytes.您的字符串是 base64 编码的 gzip 数据,因此您需要对其进行 base64 解码,而不是尝试将其编码为 UTF-8 字节。

String input = "H4sIAAAAAAAAAHNJLQtJLS4BALwLiloHAAAA";
byte[] byteCompressed = Base64.getDecoder().decode(input);
// ... rest of your code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM