import java.io.*;
public class ObjectSerializationTest {
public final static String FILE_NAME = "data.txt"; //データを保存するファイル名
public static void main(String[] args) {
Man taro = new Man("太郎", 4296); //太郎を作成
/*オブジェクトをシリアライズ*/
try {
FileOutputStream fos = new FileOutputStream(FILE_NAME);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(taro);
} catch(Exception e) {}
Man who = null; //誰?
/*オブジェクトを復元*/
try {
FileInputStream fis = new FileInputStream(FILE_NAME);
ObjectInputStream ois = new ObjectInputStream(fis);
who = (Man)ois.readObject();
} catch(Exception e) {}
System.out.println(who.getState()); //誰かの情報を得る
}
}
/*人を表すクラス*/
class Man implements Serializable {
private String name; //名前
private int id; //ID
Man(String name, int id) {
this.name = name;
this.id = id;
}
/*このオブジェクトの情報を返す*/
public String getState() {
return name + "/" + id;
}
}
|