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,


 
Ads

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

Share on Google+Share on Google+

Java Write GZIP File Example

Posted on: January 18, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: Java Write GZIP File Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads