python 和 java 之间的 Gzip 压缩和解压缩

Gzip compression and decompression between python and java

我想解压 java 中的一个字符串,该字符串在 python 中被 gzip 压缩并编码为 base64。

我想做的是对 python 中的字符串执行 gzip 压缩,我必须解压缩 java 中的压缩字符串。

首先gzip使用python中的gzip模块压缩字符串'hello'+'\r\n'+'world'然后在 python 中将该压缩字符串编码为 base64。我得到的输出是 H4sIAM7yqVcC/8tIzcnJ5+Uqzy/KSQEAQmZWMAwAAAA=

然后我使用 java 中 python 的编码压缩字符串对该字符串进行 gzip 解压缩。为此,我首先使用 DatatypeConverter.parseBase64Binary 对 java 中的该字符串执行 base64 解码,这将给出一个字节数组,然后我使用 GZIPInputStream 对该字节数组执行 gzip 解压缩。但是java中的解压输出显示为helloworld.

我在 python 中的压缩字符串中有一个 '\r\n' 但它没有显示在解压输出中。我认为这里的问题在于对该字符串执行的 base64 编码和解码。请帮我解决这个问题。

使用的字符串:

字符串='hello'+'\r\n'+'world'

java 中的预期输出:

你好
世界

输出得到:

地狱世界

这是python中的gzip压缩代码:

String ='hello'+'\r\n'+'world'

out = StringIO.StringIO()

with gzip.GzipFile(fileobj=out, mode="w") as f:

        f.write(o)

f=open('compressed_string','wb')

out.getvalue()

f.write(base64.b64encode(out.getvalue()))

f.close()

这是java中的gzip解压代码:

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("compressed_string")));

try
{
    while((nextLine=reader.readLine())!=null)
    {
        compressedStr +=nextLine;                                    
    }
    finally
    {
      reader.close();
    }
}

byte[] compressed = DatatypeConverter.parseBase64Binary(compressedStr);

decomp = decompress(compressed);

这是java中的gzip解压方法:

public static String decompress(final byte[] compressed) throws IOException {
    String outStr = "";
    if ((compressed == null) || (compressed.length == 0)) {
        return "";
    }

    if (isCompressed(compressed)) {
        GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressed));
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));

        String line;
        while ((line = bufferedReader.readLine()) != null) {
            outStr += line;
        }
    } else {
        outStr = new String(compressed);
    }

    return outStr;
}

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

Returns:

A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

bufferedReader.readLine() 按行读取

所以你需要在附加字符串时添加'\r\n'

outStr += line + "\r\n";

但你应该使用 StringBuilder