String Compression using Deflater class in java


 

String Compression using Deflater class in java

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

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 java.util.zip 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 .

Code

import java.io.*;
import java.util.zip.*;
import java.util.zip.Deflater;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

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();
    def.setLevel(Deflater.BEST_COMPRESSION);
    def.setInput(dataByte);
    def.finish();
    ByteArrayOutputStream byteArray = new ByteArrayOutputStream(
        dataByte.length);
    byte[] buf = new byte[1024];
    while (!def.finished()) {
      int compByte = def.deflate(buf);
      byteArray.write(buf, 0, compByte);
    }
    try

    {
      byteArray.close();
    }

    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

Ads