【问题标题】:compress a string in Python and how to decompress this string in java在 Python 中压缩一个字符串以及如何在 java 中解压缩这个字符串
【发布时间】:2015-11-29 16:30:29
【问题描述】:

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

x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]

如果我从 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);

Java 会抛出错误:

java.util.zip.DataFormatException: incorrect header check

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

【问题讨论】:

  • 你解决过这个问题吗?我也处于同样的困境中......

标签: java zlib


【解决方案1】:

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

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

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"

希望对某人有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多