GZip File Compression
The following example shows how to compress user given file using
GZip compression. To create a GZip compression file we need to copy bytes
from source file stream to GZIP output stream.
package com.bethecoder.tutorials.utils.zip;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class GZipFileCompression {
/**
* @param args
*/
public static void main ( String [] args ) {
String srcFilePath = "C:\\prop_file.txt" ;
String tgtZipFilePath = "C:\\prop_file.txt.gzip" ;
//gzipCompressFile(srcFilePath, tgtZipFilePath);
gzipCompressFile ( srcFilePath ) ;
}
public static void gzipCompressFile ( String srcFilePath ) {
gzipCompressFile ( srcFilePath, srcFilePath + ".gzip" ) ;
}
public static void gzipCompressFile ( String srcFilePath, String tgtZipFilePath ) {
try {
//Open source stream
FileInputStream inStream = new FileInputStream ( srcFilePath ) ;
//Open GZIP output stream
GZIPOutputStream outStream = new GZIPOutputStream ( new FileOutputStream ( tgtZipFilePath )) ;
//Copy bytes from source stream to target stream
byte [] buf = new byte [ 2048 ] ;
int len;
while (( len = inStream.read ( buf )) > 0 ) {
outStream.write ( buf, 0 , len ) ;
}
//Close all streams
inStream.close () ;
outStream.close () ;
System.out.println ( "File successfully compressed : " + tgtZipFilePath ) ;
} catch ( IOException e ) {
e.printStackTrace () ;
}
}
}
It gives the following output,
File successfully compressed : C:\prop_file.txt.gzip