Compare and decompress a Byte Array in Java

Description

The following code shows how to compare and decompress a Byte Array.

Example


/*  ww w  .java  2s.  c o m*/
import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] input = "this is a test".getBytes();

    Deflater compressor = new Deflater();
    compressor.setLevel(Deflater.BEST_COMPRESSION);

    compressor.setInput(input);
    compressor.finish();

    ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);

    byte[] buf = new byte[1024];
    while (!compressor.finished()) {
      int count = compressor.deflate(buf);
      bos.write(buf, 0, count);
    }
    bos.close();

    byte[] compressedData = bos.toByteArray();
    Inflater decompressor = new Inflater();
    decompressor.setInput(compressedData);

    bos = new ByteArrayOutputStream(compressedData.length);

    buf = new byte[1024];
    while (!decompressor.finished()) {
      int count = decompressor.inflate(buf);
      bos.write(buf, 0, count);
    }
    bos.close();

    byte[] decompressedData = bos.toByteArray();
    System.out.println(new String(decompressedData));
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Data Type »




Java Boolean
Java Byte
Java Character
Java Currency
Java Double
Java Enum
Java Float
Java Integer
Java Long
Java Short
Java Auto Grow Array
Java Array Compare
Java Array Convert
Java Array Copy Clone
Java Array Fill
Java Array Search and Sort
Java String Convert
Java String File
Java String Format
Java String Operation
Java BigDecimal
Java BigInteger