http://toptech.geekaddict.net/
Compress in java using ZIP
This task will be illustrated by an example implementation of a ZIP compressor / decompressor class.
Takes an array of bytes, then returns a byte array containing the zip-compressed content. Works the same way with decompressing.
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import java.io.ByteArrayOutputStream;
class Compressor {
private int expectedUncompressedDataSize = 16384;
private Deflater deflater;
private Inflater inflater;
private ByteArrayOutputStream bos;
protected Compressor() {
construct();
}
protected Compressor(int expectedUncompressedDataSize) {
this.expectedUncompressedDataSize = expectedUncompressedDataSize;
construct();
}
private void construct() {
deflater = new Deflater();
inflater = new Inflater();
bos = new ByteArrayOutputStream(expectedUncompressedDataSize);
}
public byte[] compress(byte[] uncompressedData) {
deflater.setInput(uncompressedData);
deflater.finish();
byte[] compressBuf = new byte[expectedUncompressedDataSize];
while (!deflater.finished()) {
int count = deflater.deflate(compressBuf);
bos.write(compressBuf, 0, count);
}
byte[] compressedData = bos.toByteArray();
reset();
return compressedData;
}
public byte[] deCompress(byte[] compressedData) {
try {
inflater.setInput(compressedData);
byte[] decompressBuf = new byte[expectedUncompressedDataSize];
while (!inflater.finished()) {
int count = inflater.inflate(decompressBuf);
bos.write(decompressBuf, 0, count);
}
byte[] decompressedData = bos.toByteArray();
reset();
return decompressedData;
} catch (Exception e) {
throw new RuntimeException("Decompressing data failed", e);
}
}
private void reset() {
bos.reset();
deflater.reset();
inflater.reset();
}
}
The class can be used like this:
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
Compressor compressor = new Compressor();
String myText =
"In this test I want compress " +
"a short text like this " +
"using ZIP, and see if " +
"it gets any smaller.";
byte[] myData = myText.getBytes();
byte[] myCompressedData = compressor.compress(myData);
byte[] myDecompressedData = compressor.deCompress(myCompressedData);
System.out.println("Uncompressed data size: " + myData.length);
System.out.println("Compressed data size: " + myCompressedData.length);
System.out.println(
"Decompressed data is correct: " +
Arrays.equals(myData, myDecompressedData
));
}
}