How can I programmatically compress a file using GZIP?

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();
        }
    }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact