Home Tutorial Java Corejava Zip How to make a gzip file in java.


Share on Google+Share on Google+
How to make a gzip file in java.
Posted on: July 12, 2010 at 12:00 AM
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 java.util.zip 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 java.util.zip.GZIPOutputStream class extends java.io.FilterIntputStream 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


import java.io.*;
import java.util.zip.*;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.zip.GZIPOutputStream;
import java.io.IOException;

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 = bufinStream.read(buf)) >= 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


Related Tags for How to make a gzip file in java.:

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.

Posted on: July 12, 2010

Recommend the tutorial

Advertisements Advertisements