Publish Your Article Here

Program: How to compress a file in GZip format?


The below example shows how to compress a file in GZip format.



public class MyFileGZipExamp {

	public void doGzip(String filePath){
		FileOutputStream fos = null;
		GZIPOutputStream gos = null;
		FileInputStream fis = null;
		try {
			fos = new FileOutputStream("C:/myGzip.gzip");
		    gos = new GZIPOutputStream(fos);
		    fis = new FileInputStream(filePath);
		    byte[] tmp = new byte[4*1024];
		    int size = 0;
		    while ((size = != -1) {
		        gos.write(tmp, 0, size);
		    System.out.println("Done with GZip...");
		} catch (IOException e) {
		} finally{
				if(fis != null) fis.close();
				if(gos != null) gos.close();
			} catch(Exception ex){}
	public static void main(String a[]){
		MyFileGZipExamp mfg = new MyFileGZipExamp();

Done with GZip...
<< Previous Program | Next Program >>

List of all class sample examples:

  1. How to compress byte array in java?
  2. How to decompress byte array in java?
  3. How to zip a single file?
  4. How to zip multiple files?
  5. How to read zip files entries or file name list?
  6. How to unzip files in java?
  7. How to generate checksum value for for a file in java?
  8. How to compress and store objects using zip utility?
  9. How to decompress the compressed objects using zip utility?
  10. How to zip a file using ZipFile class?
  11. How to compress a file in GZip format?
  12. How to uncompress a file from GZip format?
Knowledge Centre
Class, Constructor and Primitive data types
Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.
Famous Quotations
Do not confuse motion and progress. A rocking horse keeps moving but does not make any progress.
-- Alfred A. Montapert

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2019 by Nataraja Gootooru. All Rights Reserved.