【问题标题】:How to GZip decompress a compressed String data with Java code如何使用 Java 代码 GZip 解压缩压缩的字符串数据
【发布时间】:2021-10-28 05:07:12
【问题描述】:

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

我使用此代码解压缩字符串,如下所示: H4sIAAAAAAAAAAHNJLQtJLS4BALwLiloHAAAA

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

谁能帮我提供正确的解压缩代码?谢谢

【问题讨论】:

    标签: java gzip


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 1970-01-01
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 2011-11-12
      相关资源
      最近更新 更多