StudentSaver.java
import java.io.*;
import java.util.*;
/** 複数のStudentオブジェクトの情報を
ファイルへ保存する StudentSaverクラス */
public class StudentSaver {
/** 指定されたファイルの内容を読み込むメソッド */
public static void saveStudents( File file, Vector vector )
throws Exception {
try {
FileOutputStream fos = new FileOutputStream( file );
ObjectOutputStream oos = new ObjectOutputStream( fos );
for( int i=0; i<vector.size(); i++ )
oos.writeObject( vector.elementAt(i) );
oos.close();
fos.close();
}
catch( IOException e ) { // 入出力のエラーが発生
throw new Exception("書き込みエラーが発生しました");
}
}
/** 単独に実行された時に呼び出されるメソッド */
public static void main( String argv[] ) {
System.out.println( "サンプルの学生データを生成します" );
File file;
String fileName;
Student students[] = {
new Student( 1, "英文学科", 971001, "北星花子" ),
new Student( 1, "経営情報学科", 972001, "稚内太郎" ),
new Student( 2, "英文学科", 961001, "礼文トド子" ),
new Student( 2, "経営情報学科", 962001, "利尻富士男" ),
};
if( argv.length >= 1 ) fileName = argv[0];
else fileName = "student.data";
try {
file = new File( fileName );
Vector vector = new Vector();
for( int i=0; i<4; i++ )
vector.addElement( students[i] );
saveStudents( file, vector );
}
catch( Exception e ){
System.err.println( e.getMessage() );
System.exit(-1);
}
System.out.println( fileName + "に保存しました" );
}
}