相当于Java中的Qt qCompress

时间:2015-06-17 17:37:45

标签: java qt

我有基于Qt的客户端 - 服务器应用程序。客户端应用使用qCompress调用压缩数据,服务器使用qUncompress方法对其进行解压缩。

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

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

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

2 个答案:

答案 0 :(得分:1)

我知道没有库,但你可以使用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);

答案 1 :(得分:1)

对于在客户端进行qCompress并发送到Java应用程序的任何人。这个帮助函数可以帮助您解压缩它。请注意评论 - 我用它来处理POST数据,所以我不能相信数据告诉我它的大小。

/** This takes data sent from Qt's qCompress and decompresses it.
* Note that we don't use the first 4 bytes (which is the size of the decompressed data) to avoid someone crafting
* a message which says the decompressed data is 2^32-1 even when it's not.
* @param input The raw bytearray containing the whole output from qCompress
* @return The decompressed data
* @throws IOException
* @throws DataFormatException
*/
public static byte[] qUncompress(byte[] input) throws IOException, DataFormatException {
  Inflater inflater = new Inflater();
  inflater.setInput(input, 4, input.length - 4); //Strip off the first 4 bytes - this is a non standard uncompressed size that qCompress adds.
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream(input.length);
  byte[] buffer = new byte[4096];
  while (!inflater.finished()) {
     int count = inflater.inflate(buffer);
     outputStream.write(buffer, 0, count);
  }
  outputStream.close();
  return outputStream.toByteArray();
}