How can I programmatically compress a file using GZIP?
Created May 4, 2012
Tim Rohaly The java.util.zip package contains classes which allow you to
do this. Here is a program that uses these classes to GZIP-compress a file:
import java.io.*; import java.util.zip.*; public class gzip { public static void main(String[] args) { try { if (args.length != 1) { System.out.println("Usage: java gzip <inputfile>"); System.exit(1); } FileOutputStream zipfile = new FileOutputStream(args[0]+".gz"); GZIPOutputStream out = new GZIPOutputStream(zipfile); System.out.println("Writing archive " + args[0] + ".gz"); System.out.println(""); FileInputStream in = new FileInputStream(args[0]); byte[] data = new byte[2048]; int len; while ((len = in.read(data)) != -1) { out.write(data, 0, len); } in.close(); out.flush(); out.finish(); out.close(); } catch (Exception e) { System.out.println( "Exception is " + e.getMessage() ); e.printStackTrace(); } } }