SimpleZip.java
package ziptool;
import java.io.*;
import java.util.zip.*;
/** 単独のファイルを zip形式にファイルを圧縮する SimpleZip */
public class SimpleZip {
/** ファイルの読み込みの終わりを表す定数 */
protected static final int EOF = -1;
/** 最初に呼び出される処理 */
public static void main( String argv[] ) {
if( argv.length == 1 ) {
try {
File file = new File( argv[0] );
File zipFile = compressFile( file );
}
catch( FileNotFoundException e ){
System.err.println( "file not found" );
}
catch( ZipException e ){
System.err.println( "Zip error..." );
}
catch( IOException e ){
System.err.println( "IO error..." );
}
}
else {
System.out.println( "Usage:java GZip file" );
}
}
/** 与えられたファイルを圧縮する */
public static File compressFile( File file )
throws FileNotFoundException,
ZipException,IOException {
File zipFile = new File( file.getName() + ".zip" );
try {
BufferedInputStream bis
= new BufferedInputStream(
new FileInputStream( file ) );
ZipOutputStream zos
= new ZipOutputStream(
new FileOutputStream( zipFile ) );
ZipEntry target = new ZipEntry( file.getPath() );
zos.putNextEntry( target );
/* バッファリングは自動的に行われるので、ここで指定している
バッファサイズは、特別に意味は持たない */
byte buf[] = new byte[1024];
int count;
while( ( count = bis.read( buf, 0, 1024 ) )
!= EOF ) {
zos.write( buf, 0, count );
}
bis.close();
zos.closeEntry();
zos.close();
return zipFile;
}
catch( FileNotFoundException e ){
throw e;
}
catch( ZipException e ){
throw e;
}
catch( IOException e ){
throw e;
}
}
}