在Python中压缩字符串以及如何在java中解压缩此字符串

Sea*_*ean 0 java zlib

在我的服务器端,我使用zlib python库压缩(zlib.compress())一个字符串,并将它插入redis.在我的redis中,它显示:

x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]
Run Code Online (Sandbox Code Playgroud)

如果我从redis读到python并使用python zlib.decompress(),它就可以了.它可以打印"Hello World".

我怎么能在java中做到这一点?

我从Java 7官方文档中尝试了这段代码.

String temp ="x\\xda\\xcbH\\xcd\\xc9\\xc9\\x07\\x00\\x06,\\x02\\x15";
byte[] output=temp.getBytes();
System.out.println(new String(output));
// Decompress the bytes
Inflater decompresser = new Inflater();
decompresser.setInput(output, 0,output.length);
byte[] result = new byte[10000];
int resultLength = decompresser.inflate(result);
decompresser.end();

// Decode the bytes into a String
String outputString = new String(result, 0, resultLength, "UTF-8");
System.out.println(outputString);
Run Code Online (Sandbox Code Playgroud)

Java会抛出错误:

java.util.zip.DataFormatException: incorrect header check
Run Code Online (Sandbox Code Playgroud)

我应该怎么解压缩呢?从其他帖子中,我发现人们正在使用GZIPInputStream.有任何性能差异吗?

dac*_*una 5

很晚了,但今天我发现自己正在解决同样的问题.我设法像这样解决它:

Python代码(压缩):

import zlib
import base64

data = "Hello World"
c_data = zlib.compress(data)
# to be able to transmit the data we need to encode it
final_data = base64.b64encode(c_data)
data_size = len(data) # we need this to decompress in java
Run Code Online (Sandbox Code Playgroud)

Java代码(解压缩),我使用Java 8,所以我们有一个内置的base64解码器,对于其他java版本,有很多解码器.另外为了保持简短,我没有把异常处理代码:

String dataFromPython = ... //put your final_data here
byte[] decoded = Base64.getDecoder().decode(dataFromPython);
Inflater decompresser = new Inflater();
decompresser.setInput(decoded, 0, decoded.length);
byte[] result = new byte[data_size]; //remember the data_size var from python?
int resultLength = decompresser.inflate(result);
decompresser.end();
//Assumptions: python 2, ASCII string
String final_data = new String(result, "US-ASCII");
System.out.prinln(final_data); //prints "Hello World"
Run Code Online (Sandbox Code Playgroud)

希望它能帮助别人!