Home Java Examples Io Java Write GZIP File Example



Java Write GZIP File Example
Posted on: January 18, 2012 at 12:00 AM
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

Related Tags for Java Write GZIP File Example:


More Tutorials from this section

Ask Questions?    Discuss: Java Write GZIP File Example  

Post your Comment


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

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.