Compress Byte Array Using Deflater - Java File Path IO

Java examples for File Path IO:Byte Array

Description

Compress Byte Array Using Deflater

Demo Code


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

public class Main {
  public static void main(String args[]) {
    String str = "this is a test";

    byte[] bytes = str.getBytes();

    Deflater deflater = new Deflater();

    deflater.setInput(bytes);//www. ja  v  a 2s  . c o  m

    deflater.finish();

    ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);

    byte[] buffer = new byte[1024];

    while (!deflater.finished()) {
      int bytesCompressed = deflater.deflate(buffer);
      bos.write(buffer, 0, bytesCompressed);
    }

    try {
      bos.close();
    } catch (Exception ioe) {
      System.out.println("Error while closing the stream : " + ioe);
    }

    byte[] compressedArray = bos.toByteArray();

    System.out.println("Byte array has been compressed!");
    System.out.println("Size of original array is:" + bytes.length);
    System.out.println("Size of compressed array is:" + compressedArray.length);

  }
}
 

Result


Related Tutorials