ZipGet.java
package ziptool;
import java.io.*;
import java.util.*;
import java.util.zip.*;
/** zip形式のアーカイブファイルから
目的のファイルを取り出して保存する ZipGet */
public class ZipGet {
/** データの読み込み終了を表す定数 */
public static final int EOF = -1;
/** 最初に呼び出される処理 */
public static void main( String argv[] ) {
Enumeration enum;
if( argv.length == 2 ) {
try {
ZipFile zipFile = new ZipFile( argv[0] );
enum = zipFile.entries();
boolean foundFlag = false;
while( enum.hasMoreElements() ) {
ZipEntry target
= (ZipEntry)enum.nextElement();
if( target.getName().equals( argv[1] ) ) {
getEntry( zipFile, target );
foundFlag = true;
break;
}
}
if( !foundFlag )
System.err.println(
"target file not found in the zipfile" );
}
catch( FileNotFoundException e ){
System.err.println( "zipfile not found" );
}
catch( ZipException e ){
System.err.println( "zip error..." );
}
catch( IOException e ){
System.err.println( "IO error..." );
}
}
else {
System.err.println(
"Usage:java ZipGet zipfile targetname" );
}
}
/** 与えられた ZipEntry の内容を取り出して再生する */
public static void getEntry( ZipFile zipFile,
ZipEntry target )
throws ZipException,IOException {
try {
File file = new File( target.getName() );
BufferedInputStream bis
= new BufferedInputStream(
zipFile.getInputStream( target ) );
File dir = new File( file.getParent() );
dir.mkdirs(); // ディレクトリをリカーシブに作成する
BufferedOutputStream bos
= new BufferedOutputStream(
new FileOutputStream( file ) );
int c;
while( ( c = bis.read() ) != EOF ) {
bos.write( (byte)c );
}
bos.close();
}
catch( ZipException e ){
throw e;
}
catch( IOException e ){
throw e;
}
}
}