GZCat.java



package ziptool;

import java.io.*;
import java.util.zip.GZIPInputStream;

/** gzip形式に圧縮されたテキストファイルの内容を表示する GZCat */

public class GZCat {

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

     public static void main( String argv[] ) {

          if( argv.length == 1 ) {
              try {
                // 識別子 .gz が省略された場合にも対応する
                   int n = argv[0].length();
                   String bodyName;
                   if( argv[0].regionMatches( n-3, ".gz", 0, 3 ) )
                       bodyName = argv[0].substring( 0, n-3 );
                   else
                       bodyName = argv[0];

                   File pressed = new File( bodyName + ".gz" );
                   displayFile( pressed );
              }
              catch( FileNotFoundException e ){
                     System.err.println( "file not found" );
              }
              catch( IOException e ){
                     System.err.println( "IO error..." );
              }
         }
         else {
               System.err.println(
                             "Usage:java GZipCat gzipfile" );
         }
   }

  /** 与えられたファイルの内容を表示する */

     public static void displayFile( File file )
                 throws FileNotFoundException,IOException {

          try {
               BufferedReader br =
                  new BufferedReader(
                     new InputStreamReader(
                        new GZIPInputStream(
                           new FileInputStream( file ) ) ) );

               PrintWriter pw
                       = new PrintWriter( System.out, true );
               String s;
               while( ( s = br.readLine() ) != null ) {
                  pw.println( s );
               }
          }
          catch( FileNotFoundException e ){
                 throw e;
          }
          catch( IOException e ){
                 throw e;
          }
     }
}