Zip the File in Java Program

  1. import java.util.zip.GZIPInputStream;  
  2. import java.io.OutputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.IOException;  
  7.   
  8. public class JavaUncompress{  
  9.     public static void main(String args[]){  
  10.         try{  
  11.             //To Uncompress GZip File Contents we need to open the gzip file.....  
  12.             if(args.length<=0){  
  13.                 System.out.println("Please enter the valid file name");  
  14.             }  
  15.             else{  
  16.                 String inFilename = args[0];  
  17.                 System.out.println("Opening the gzip file.......................... :  opened");  
  18.                 GZIPInputStream gzipInputStream = null;  
  19.                 FileInputStream fileInputStream = null;  
  20.                 gzipInputStream = new GZIPInputStream(new FileInputStream(inFilename));  
  21.                 System.out.println("Opening the output file............. : opened");  
  22.                 String outFilename = inFilename +".pdf";  
  23.                 OutputStream out = new FileOutputStream(outFilename);  
  24.                 System.out.println("Trsansferring bytes from the compressed file to the output file........:  Transfer successful");  
  25.                 byte[] buf = new byte[1024];  //size can be changed according to programmer's need.  
  26.                 int len;  
  27.                 while ((len = gzipInputStream.read(buf)) > 0) {  
  28.                     out.write(buf, 0, len);  
  29.                 }  
  30.                 System.out.println("The file and stream is ......closing.......... : closed");   
  31.                 gzipInputStream.close();  
  32.                 out.close();  
  33.             }  
  34.         }  
  35.         catch(IOException e){  
  36.             System.out.println("Exception has been thrown" + e);  
  37.         }  
  38.     }