ZipCat.java



import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipException;

/** zip形式のファイルから目的のファイル名の内容を取り出して表示する ZipCat */

public class ZipCat {

  /** zip形式のファイル */

     public static ZipFile zf;

  /** バッファサイズ */

     public static final int BUFSIZE = 1024;

  /** データの読み込み終了を表す定数 */

     public static final int EOF = -1;

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

     public static void main( String argv[] ) {

          Enumeration enum;

          if( argv.length == 2 ) {
              try {
                   zf = new ZipFile( argv[0] );
                   enum = zf.entries();

                   boolean foundFlag = false;
                   while( enum.hasMoreElements() ) {

                         ZipEntry target = (ZipEntry)enum.nextElement();
                         if( target.getName().equals( argv[1] ) ) {
                             readEntry( target );
                             foundFlag = true;
                             break;
                         }
                   }
                   if( !foundFlag )
                         System.out.println( "target file not found in the zipfile" );
              }
              catch( FileNotFoundException e ){
                     System.out.println( "zipfile not found" );
              }
              catch( ZipException e ){
                     System.out.println( "zip error..." );
              }
              catch( IOException e ){
                     System.out.println( "IO error..." );
              }
         }
         else {
               System.out.println( "Usage:java ZipCat zipfile targetname" );
         }
   }

  /** 与えられた ZipEntry の内容を表示する */

     public static void readEntry( ZipEntry target )
                                   throws ZipException,IOException {

            char[] buf = new char[BUFSIZE];

            try {
                 InputStream is = zf.getInputStream( target );
                 InputStreamReader isr = new InputStreamReader( is );
                 int count;
                 while( ( count = isr.read( buf, 0, BUFSIZE ) ) != EOF ) {
                      System.out.print( new String( buf, 0, count ) );
                 }
            zf.close();
            }
            catch( ZipException e ){
                   throw e;
            }
            catch( IOException e ){
                   throw e;
            }
      }
}