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

标签 java zlib

在我的服务器端,我使用 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。有性能差异吗?

最佳答案

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

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"

希望对大家有帮助!

关于java - 在Python中压缩字符串以及如何在java中解压缩该字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33985096/

相关文章:

linux - 将 libgio.so 与 libz.so 链接时未解析的符号 (linux)

perl - 从 Perl 中具有数据偏移量的文件加载 zlib 压缩数据

c++ - 使用zlib1.2.7解压gzip数据,如何获取压缩包中的文件名

java - 具有 Spring Boot 和事务边界的 graphql-spqr

Java - 事件处理设计

java - Dijkstra 算法与 Neo spring boot

c++ - 使用 zlib 压缩目录

java - Alfresco 中以编程方式提供多语言内容

java - MySQL插入字段列表中的未知列

c++ - 在 Linux 上使用 zlib 编译 boost