Home Java Examples Io Java Write GZIP File Example
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Java Write GZIP File Example

Advertisement
To add a file in GZIP format you need to use java.util.zip.GZIPOutputStream class. An example of writing a text file in GZIP format is given below,

Java Write GZIP File Example

To add a file in GZIP format you need to use java.util.zip.GZIPOutputStream class. An example of writing a text file in GZIP format is given below,

JavaWriteToGZIPFileExample.java

import java.io.FileOutputStream;
import java.io.FileInputStream;

import java.io.IOException;

import java.util.zip.GZIPOutputStream;

public class JavaWriteToGZIPFileExample{
	public static void main(String[] args) throws IOException{
		        
		/* The new file name which you will get */
		String newFileName = "myNewCompressedFile.gzip";		

		FileOutputStream fileOutputStream = new FileOutputStream(newFileName);

		/* GZIPOutputStream class to compress the file */
		GZIPOutputStream outputStream = new GZIPOutputStream(fileOutputStream);
	
		/* The file which you have to compress */
		String fileToCompress = "myTextFile.txt";
		FileInputStream inputStream = new FileInputStream(fileToCompress);
	
		/* Creating a Buffer to Transfer a file */
		byte []buffer = new byte[1024];
		int length;
		while ((length = inputStream.read(buffer)) > 0) {
			outputStream.write(buffer, 0, length);
		}

		/* Finally closing the GZIPOutputStream and FileInputStream classes */
		inputStream.close();				
		outputStream.close();
	}
}

Download Select Source Code

Advertisements

Liked it!  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.

Posted on: January 18, 2012

Ask Questions?    Discuss: Java Write GZIP File Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com