Compressing a File : GZIP « File Input Output « Java






Compressing a File

  
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class CompressIt {
  public static void main(String[] args) {
    String filename = args[0];
    try {
      File file = new File(filename);
      int length = (int) file.length();
      FileInputStream fis = new FileInputStream(file);
      BufferedInputStream bis = new BufferedInputStream(fis);
      ByteArrayOutputStream baos = new ByteArrayOutputStream(length);
      GZIPOutputStream gos = new GZIPOutputStream(baos);
      byte[] buffer = new byte[1024];
      int bytesRead;
      while ((bytesRead = bis.read(buffer)) != -1) {
        gos.write(buffer, 0, bytesRead);
      }
      bis.close();
      gos.close();
      System.out.println("Input Length: " + length);
      System.out.println("Output Length: " + baos.size());
    } catch (FileNotFoundException e) {
      System.err.println("Invalid Filename");
    } catch (IOException e) {
      System.err.println("I/O Exception");
    }
  }
}
           
         
    
  








Related examples in the same category

1.GZip with GZIPOutputStream
2.Ungzip with GZIPInputStream
3.Uncompress a file in the GZIP format
4.Compressing a File in the GZIP Format
5.Uncompressing a File in the GZIP Format
6.Compress a file in the GZIP format
7.gzipping files and zipping directories
8.Compress Java objects
9.Decompress Java objects
10.Compressed socket
11.Compress a list of files passed in from command line
12.GZIP compress
13.Read some data from a gzip file
14.A collection of utility methods for working on GZIPed data
15.Reads GZIP, Zip, and Jar files
16.GZIP Filter, response stream and Response Wrapper