GZip.java
package ziptool;
import java.io.*;
import java.util.zip.GZIPOutputStream;
/** 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.err.println( "file not found" );
}
catch( IOException e ){
System.err.println( "IO error..." );
}
}
else {
System.err.println( "Usage:java GZip file" );
}
}
/** 与えられたファイルを圧縮する */
public static boolean compressFile( File orig )
throws FileNotFoundException,IOException {
boolean flag = false;
try {
BufferedInputStream bis
= new BufferedInputStream(
new FileInputStream( orig ) );
BufferedOutputStream bos
= new BufferedOutputStream(
new GZIPOutputStream(
new FileOutputStream(
new File( orig.getName() + ".gz" ) ) ) );
/* 1バイト読み込んでは1バイト書き出すのはまずいように見えるが、
実際にはバッファリングを自動的に行っているので問題ない */
int c;
while( ( c = bis.read() ) != EOF ) {
bos.write( (byte)c );
}
bis.close();
bos.close();
flag = true;
}
catch( FileNotFoundException e ){
throw e;
}
catch( IOException e ){
throw e;
}
return flag;
}
}