GZip.java



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

/** gzip形式にファイルを圧縮する GZip */

public class GZip {

  /** ファイルの読み込みの終わりを表す定数 */

     protected static final int EOF = -1;

  /** 最初に呼び出される処理 */

     public static void main( String argv[] ) {

          if( argv.length == 1 ) {
              try {
                   File file = new File( argv[0] );
                   boolean successFlag = compressFile( file );
                   if( successFlag ) file.delete();
              }
              catch( FileNotFoundException e ){
                     System.out.println( "file not found" );
              }
              catch( IOException e ){
                     System.out.println( "IO error..." );
              }
         }
         else {
               System.out.println( "Usage:java GZip file" );
         }
   }

  /** 与えられたファイルを圧縮する */

     public static boolean compressFile( File orig )
                         throws FileNotFoundException,IOException {

            boolean flag = false;
            try {
                 FileInputStream fis = new FileInputStream( orig );
                 BufferedInputStream bis = new BufferedInputStream( fis );

                 File comp = new File( orig.getName() + ".gz" );
                 FileOutputStream fos = new FileOutputStream( comp );
                 GZIPOutputStream gzos = new GZIPOutputStream( fos );

   /* 1バイト読み込んでは1バイト書き出すのはまずいように見えるが、
      実際にはバッファリングを自動的に行っているので問題ない      */
                 int c;
                 while( ( c = bis.read() ) != EOF ) {
                    gzos.write( (byte)c );
                 }
            bis.close();   // fis より先にクローズすること
            fis.close();
            gzos.close();  // fos より先にクローズすること
            fos.close();
            flag = true;
            }
            catch( FileNotFoundException e ){
                   throw e;
            }
            catch( IOException e ){
                   throw e;
            }
            return flag;
      }
}