相当于Java中的Qt qCompress

我有基于Qt的客户端 – 服务器应用程序.客户端应用程序使用qCompress调用压缩数据,服务器使用qUncompress方法解压缩数据.

我现在需要用Java编写一个与同一服务器通信的新客户端应用程序.为了正确解压缩,我需要确保使用与qCompress相同的压缩.

浏览网页,看来Qt可能正在使用zip压缩.我看了一下java zip相关的类.但是,我不确定它是否有效.例如,ZipEntry构造函数需要名称作为参数.但是,Qt不需要任何名称作为参数.

如果您能确认Java zip类是否与Qt压缩/解压缩兼容,我将不胜感激.如果它们兼容,那么我的参数对ZipEntry构造函数的价值是多少?问候.

最佳答案 没有我知道的库,但是你可以使用java.util.zip.Deflater压缩数据并在字节数组的开头添加未压缩数据的大小:

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;

final int MAX_DATA = 1024;
final int SIZE_LENGTH = 4;

// Input data
byte[] uncompressed = "hello".getBytes(Charset.forName("UTF-8"));

// This is simplistic, you should use a dynamic buffer
byte[] buffer = new byte[MAX_DATA];

// Add the uncompressed data size to the first 4 bytes
ByteBuffer.wrap(buffer, 0, SIZE_LENGTH).putInt(uncompressed.length);

// Compress it
Deflater deflater = new Deflater();
deflater.setInput(uncompressed);
deflater.finish();
// Write past the size bytes when compressing
int size = deflater.deflate(buffer, SIZE_LENGTH, buffer.length - SIZE_LENGTH);
// TODO maybe check the returned size value to increase the buffer size?
if (!deflater.finished()) throw new DataFormatException("Buffer size exceeded");

// Compressed data that can be consumed by qUncompress
byte[] compressed = Arrays.copyOf(buffer, SIZE_LENGTH + size);
点赞