Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Qt qCompress in Java

Tags:

java

qt

I have Qt based client-server application. The client app compresses data using qCompress call and the server uncompresses it using qUncompress method.

I now need to write a new client app in Java that communicates with the same server. For proper uncompressing, I need to ensure that I use the same compression as qCompress is doing.

Browsing the net, it appears Qt may be using zip compression. I looked at java zip related classes. However, I am not sure if it will work. For example, ZipEntry constructor requires a name as a parameter. However, Qt does not require any names as parameter.

I would appreciate it if you can confirm whether Java zip classes are compatible with Qt compression/uncompression. If they are compatible, what would be the value of my parameter to ZipEntry constructor? Regards.

like image 437
Peter Avatar asked Oct 31 '22 01:10

Peter


1 Answers

There is no library that I am aware however you can use java.util.zip.Deflater to compress the data and add the size of the uncompressed data in the beginning of the byte array:

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);
like image 107
John L. Jegutanis Avatar answered Nov 15 '22 04:11

John L. Jegutanis