Intro
This examples, will show how to compress a byte array using Deflater class.
Example
package com.freesamplecode.java.zip;
import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
public class CompressByteArrayDeflaterDemo {
public static void main(String[] args){
String str = "This tutorials will demonstrates how to compress a byte array using Deflater class";
//get byte a string str
byte[] bytes = str.getBytes();
//create a deflater object
Deflater deflater = new Deflater();
deflater.setInput(bytes);
deflater.finish();
ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length);
byte[] buffers = new byte[2048];
while(!deflater.finished()){
int byteCompressed = deflater.deflate(buffers);
baos.write(buffers, 0, byteCompressed);
}
byte[] byteCompressedArray = baos.toByteArray();
System.out.println("Size of original byte array : "+bytes.length);
System.out.println("Size of compressed byte array : "+byteCompressedArray.length);
}
}
Output
Size of original byte array : 82 Size of compressed byte array : 76

0 comments: