Share on Google+Share on Google+

How to make a gzip file in java.

In this tutorial you will see how to make a gzip file from any given file.

Make a gzip file from any given file.

In this tutorial, we will discuss how to create GZIP file by using GZIPOutputStream class.  The GZIPOutputStream  class is available in package. The GZIPOutputStream class create a input stream for compressing data in GZIP format file. The FileInputStream class create an input stream for reading data from the file.

In this example, we will create a GZIP file from a given file. First of all, we will read given file with the help of  FileInputStream class and then after store data in a internal buffer. The BufferedInputStream class  read bytes from  input stream. The write method of  GZIPOutputStream class write array of byte onto compress output stream.. 

GZIPOutputStream API:

The class extends class. It provides the following methods:

Return type Method Description
void  finish() The finish() method finish writing data on associated output stream and not close stream.
void  close() The close() method close writing data on associated output stream and close stream.
void write(byte[] b, int offset, int length) The write(..) method writes an array of bytes onto compress output stream



class Gzipcompress {
    static String sourcefile = "testfile.txt";

    public static void main(String args[]) {
        try {
      File oldfile = new File(sourcefile);
      System.out.println(" Given file name is  : " + oldfile);
      FileInputStream finStream = new FileInputStream(oldfile);
      BufferedInputStream bufinStream = new BufferedInputStream(finStream);
      FileOutputStream outStream = new FileOutputStream(oldfile);
      GZIPOutputStream goutStream = new GZIPOutputStream(outStream);  
      byte[] buf = new byte[1024];
      int i;
      while ((i = >= 0) {
        goutStream.write(buf, 0, i);
      System.out.println("Created  GZIP file is " + oldfile + ".gz");
      System.out.println("GZIP File successfully created");
      }catch (IOException e) {
        System.out.println("Exception is" + e.getMessage());

Following is the output if you run the application:

C:\>java Gzipcompress
Given file name is : testfile.txt
Created GZIP file is testfile.txt.gz
GZIP File successfully created

Download this code



Posted on: July 12, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.