关于base64:Python和Java之间的Gzip压缩和解压缩

Gzip compression and decompression between python and java

我想在经过gzip压缩并在python中编码为base64的java中解压缩字符串。

我想做的是在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压缩代码:

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

out = StringIO.StringIO()

使用gzip.GzipFile(fileobj = out,mode =" w")作为f:

1
    f.write(o)

f =打开('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")));;

尝试
{

1
2
3
4
5
6
7
8
9
10
11
12
13
while((nextLine=reader.readLine())!=null)

{

    compressedStr +=nextLine;                                    

}

finally
{

  reader.close();
}

}

byte []压缩= DatatypeConverter.parseBase64Binary(compressedStr);

decomp =解压缩(压缩);

这是java中的gzip解压缩方法:

公共静态字符串decompress(最终字节[]压缩)抛出IOException {

1
2
3
4
5
6
7
8
9
10
11
    String outStr ="";

    if ((compressed == null) || (compressed.length == 0)) {

        return"";

    }

    if (isCompressed(compressed)) {

        GZIPInputStream gis = new GZIPInputStream(new

ByteArrayInputStream(压缩));

1
        BufferedReader bufferedReader = new BufferedReader(new

InputStreamReader(gis," UTF-8"));

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
        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 ('
'), a carriage return ('
'), 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"

1
2
3
outStr += line +"

"
;

但您应该使用StringBuilder