14/07/2015

[Java] Gzip deflate and inflate

Here's a simple class to deflate and inflate Gzip files in Java. It uses Apache Commons compress (those methods are also in Apache Commons library) for some utility methods, but they can be replaced with pure Java versions.

 import org.apache.commons.compress.utils.IOUtils;  
 import java.io.FileInputStream;  
 import java.io.FileOutputStream;  
 import java.util.zip.GZIPInputStream;  
 import java.util.zip.GZIPOutputStream;  
   
 public static class GZ{  
   
      public static void gzDeflate(String in, String out){  
   
                try{  
                     FileInputStream fin = new FileInputStream(in);//file to compress  
                     FileOutputStream fout = new FileOutputStream(out);//output file  
                     GZIPOutputStream gz_out = new GZIPOutputStream(fout);//gzipped file  
                       
                     //creates gzip  
                     IOUtils.copy(fin, gz_out);  
                     /*if you do not want to use Apache libraries, you can read bytes from fin and write them to gz_out in a loop*/  
                }  
                catch(Exception e){  
                     //do something  
                }  
                finally{  
                     //DO NOT close in any other order!!  
                     IOUtils.closeQuietly(gz_out);  
                     IOUtils.closeQuietly(fout);  
                     IOUtils.closeQuietly(fin);   
                     /*if you do not want to use Apache libraries you can check if object is not null and close it*/  
                }  
      }  
   
      public static void gzInflate(String in, String out){  
   
                try{  
                     FileInputStream fin = new FileInputStream(in);//file to decompress  
                     GZIPInputStream gz_in = new GZIPInputStream(fin);  
                     FileOutputStream fout = new FileOutputStream(out);//output file  
                       
                     //inflates gzip  
                     IOUtils.copy(gz_in, fout);  
                     /*if you do not want to use Apache libraries, you can read bytes from gz_in and write them to fout in a loop*/  
                }  
                catch(Exception e){  
                     //do something  
                }  
                finally{  
                     //DO NOT close in any other order!!  
                     IOUtils.closeQuietly(fout);  
                     IOUtils.closeQuietly(gz_in);  
                     IOUtils.closeQuietly(fin);   
                     /*if you do not want to use Apache libraries you can check if object is not null and close it*/  
                }  
      }  
 }  


As you can see, all usual checks have been omitted but I'm sure you'll check for file existence, etc.. beforehand

No comments:

Post a Comment

With great power comes great responsibility