CatCommand.java
import java.io.File;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.io.IOException;
/** ファイルの内容を読み込み、標準出力へ表示する CatCommandクラス */
public class CatCommand {
/** 最初に呼び出されるメソッド */
public static void main( String argv[] ) {
File file; // 読み込むファイル
FileReader fr; // ファイルを読み込むメソッドを提供
OutputStreamWriter osw; // 標準出力に表示するメソッドを提供
try{
if( argv.length != 1 ) { // コマンド引数の指定が不正
System.err.println("Usage: java CatCommand filename");
System.exit(0);
}
file = new File( argv[0] ); // ファイルをオープン
if( !file.isFile() ) { // 通常のファイルではない
System.err.println( argv[0] + "is not a normal file.");
System.exit(0);
}
if( !file.canRead() ) { // ファイルの読み込み許可がない
System.err.println("File" + argv[0] + "not readable.");
System.exit(0);
}
fr = new FileReader( file );
osw = new OutputStreamWriter( System.out );
int c;
while( ( c = fr.read() ) != -1 ) { // 1文字単位で入出力
osw.write( c );
}
osw.flush(); // 標準出力のバッファの強制フラッシュ
}
catch( NullPointerException e ) { // 文字列データがない
System.err.println("Usage: java CatCommand filename");
System.exit(0);
}
catch( IOException e ) { // 入出力のエラーが発生
System.err.println("IO Error....");
System.exit(0);
}
}
}