如何使用 Java 代码 GZip 解压缩压缩的字符串数据

How to GZip decompress a compressed String data with Java code

我有一些代码可以解压缩 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));
    }

我使用这段代码解压缩一个字符串,如下所示: H4sIAAAAAAAAAHNJLQtJLS4BALwLiloHAAAA

但是这段代码解压了一个意想不到的字符串,虽然我可以在网络上正常在线解压

谁能帮我给出正确的解压代码?谢谢

您的字符串是 base64 编码的 gzip 数据,因此您需要对其进行 base64 解码,而不是尝试将其编码为 UTF-8 字节。

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