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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With