Compress a Byte Array


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

public class Main {
  public static void main(String[] argv) throws Exception {
    byte[] input = "asdf".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();
  }
}
Home 
  Java Book 
    Runnable examples  

Zip File:
  1. List the contents of a zip file
  2. Compress a Byte Array
  3. Zip a file
  4. Zip a directory including its subdirectories recursively
  5. Decompress(unzip) a Byte Array