Share on Google+Share on Google+

String Compression using Deflater class in java

In this tutorial you will see the use of Deflater class for compressing string.

String Compression using Deflater class in java.

In this tutorial, we will define the use of Deflater class. The Deflater class is used to compressed data by using ZLIB library. The Deflater class is available in package .The getBytes() method get byte of string.
     Deflater is use Dictionary-Based Compression .This tries to replace repeated patterns of the data with the reference of the first occurrence of repeated pattern.

In the given Example, we will compress data. The Defleter class create a deflater object for compressing data. The setLevel() method of Deflater class set level of compression. The setInput() method of Deflater class is used to input data for compression. The ByteArrayOutputStream class create output stream  in which data is written. The deflater() method of Deflater class store compressed data into buffer.

About Deflater API:

Return Type Method Description 
int deflater(byte[] b) The deflater() method store compressed data into  associated buffer.
void setLevel() The setLevel() method set te leve of compression.
void setInput() The setInput() method set data for compression.
void finish() Thefinish() method define that compression will be finished .



public class DeflaterDemo {
  public static void main(String args[]) {
    String data = new String(
    "ab cd ab cd ab ab cd ab cd ab ab cd ab cd ab ab cd ab cd ab");
    byte[] dataByte = data.getBytes();
    System.out.println("Compression Demo");
    System.out.println("Actual Size of String : " + dataByte.length);
    Deflater def = new Deflater();
    ByteArrayOutputStream byteArray = new ByteArrayOutputStream(
    byte[] buf = new byte[1024];
    while (!def.finished()) {
      int compByte = def.deflate(buf);
      byteArray.write(buf, 0, compByte);


    catch (IOException ioe) {
      System.out.println("When we will close straem error : " + ioe);

    byte[] comData = byteArray.toByteArray();

    System.out.println("Compressed  size of String : " + comData.length);

Following is the output if you run the application:

C:\>java DeflaterDemo
Compression Demo
Actual Size of String : 59
Compressed size of String : 19


Posted on: July 15, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null