解答例 - 実習課題3 - 4.オブジェクトのシリアライズ
(実習課題3)
以下のプログラムを作成しなさい。
- 実習課題1で作成したオブジェクトを読み込むプログラム。読み込んだオブジェクトを標準出力に表示する事。
- 読み込むファイルは標準入力から指定する事。プログラムの実行時に引数として指定するのは不可。
- 読み込むオブジェクトは2つ以上。
解答例
/**
* ObjectInputExample.java
* TECHSCORE Java 入出力4章 実習課題3
*
* まずObjectOutputExampleを実行して、オブジェクトを保存したファイルを作成する
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
package com.techscore.io.chapter4.exercise3;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
public class ObjectInputExample {
public static void main(String[] args) {
try {
System.out.println("ファイル名を指定してください");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String name = reader.readLine();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(name));
StudentExample student1 = (StudentExample)in.readObject();
StudentExample student2 = (StudentExample)in.readObject();
in.close();
System.out.println("ファイルを読み込みました\n");
System.out.println("id:" + student1.getId());
System.out.println("name:" + student1.getName());
System.out.println("course:" + student1.getCourse());
System.out.println("lebel:" + student1.getLebel());
System.out.println();
System.out.println("id:" + student2.getId());
System.out.println("name:" + student2.getName());
System.out.println("course:" + student2.getCourse());
System.out.println("lebel:" + student2.getLebel());
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

