我想在java中解压缩一个字符串,该字符串在python中被gzip压缩并编码为base64。
我想做的是在python中对字符串执行gzip压缩,然后我必须在java中解压缩压缩后的字符串。
首先在python中使用gzip模块压缩字符串'hello'+'rn'+'world',然后在python中将压缩字符串编码为base64。我得到的输出是H4sIAM7yqVcC/8tIzcnJ5+Uqzy/KSQEAQmZWMAwAAAA=
然后我使用java中python的编码压缩字符串来gzip解压缩该字符串。为此,我首先使用DatatypeConverter.parseBase64Binary
在java中对该字符串执行base64解码,这将给出一个字节数组,然后我使用GZIPInputStream
对该字节数组执行gzip解压缩。但是java中解压后的输出显示为helloworld。
我有一个'rn'在python的压缩字符串但它不会显示在解压后的输出中。我认为这里的问题是在base64编码和解码上执行的字符串。请帮我解决这个问题。
字符串使用:
string = 'hello'+'rn'+'world'
java期望输出:
你好
世界
输出了:
helloworld
这是python中的gzip压缩代码:
String ='hello'+'rn'+'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;
}
读取一行文本。换行符('n')、回车符('r')或回车符后紧接换行符中的任何一种都认为行结束。
的回报:
包含本行内容的字符串,不包括任何行终止字符,如果流末尾有,则为空达到
bufferedReader.readLine()
按行读取
所以你需要在字符串
后面加上'rn'outStr += line + "rn";
但是你应该使用StringBuilder