How can I programmatically uncompress a file that has been compressed using GZIP?

Tim Rohaly

The java.util.zip package has classes which let you do this. Here is a program using these classes that will GZIP-uncompress a file:

import java.io.*;
import java.util.zip.*;

public class gunzip {

    public static void main(String[] args) {
        try {
            if (args.length != 1) {
                System.out.println("Usage: java gunzip <inputfile>");
                System.exit(1);
            }

            String filename = null;
            if (args[0].endsWith(".gz")) {
                filename = args[0].substring(0, args[0].lastIndexOf(".gz"));
            }
            else {
                System.out.println("Inputfile must have extension .gz");
                System.exit(1);
            }

            FileOutputStream out = new FileOutputStream(filename);

            System.out.println("Extracting archive " + args[0]);
            System.out.println("");

            FileInputStream  file = new FileInputStream(args[0]);
            GZIPInputStream  in   = new GZIPInputStream(file);

            byte[] data = new byte[2048];
            int len;
            while ((len = in.read(data)) != -1) {
                out.write(data, 0, len);
            }
            in.close();
            out.flush();
            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