|
|
|
import java.io.*;
|
|
|
|
class Student
implements Serializable {
|
|
//static final long serialVersionUID =
4259457944890225731L;
|
|
|
|
private String name;
|
|
//private String prename =
"Hans"; // added for second version
|
|
private int age;
|
|
|
|
public Student(String name, int age) {
|
|
System.out.println("Student()");
|
|
this.name = name;
|
|
this.age
= age;
|
|
}
|
|
|
|
public String toString() {
|
|
return name + ", " + age;
|
|
// return
(prename!=null?prename:"") + " " + name + ", "
+ age;
|
|
}
|
|
}
|
|
|
|
class WriteStudent {
|
|
public static void main(String [] args)
throws Exception {
|
|
Student p = new
Student("Alfred", 22);
|
|
ObjectOutputStream oos = new
ObjectOutputStream(new FileOutputStream("Student.ser"));
|
|
|
|
try {
|
|
System.out.println(p);
|
|
oos.writeObject(p);
|
|
|
|
Student[] s = new Student[2];
|
|
s[0] = p;
|
|
s[1] = p;
|
|
oos.writeObject(s);
|
|
}
|
|
finally {
|
|
try {oos.flush();} catch (IOException
ioe) {}
|
|
try {oos.close();} catch (IOException
ioe) {}
|
|
}
|
|
}
|
|
}
|
|
|
|
class ReadStudent {
|
|
public static void main(String [] args)
throws Exception {
|
|
ObjectInputStream ois = new
ObjectInputStream(new FileInputStream("Student.ser"));
|
|
try {
|
|
Object o = ois.readObject();
|
|
System.out.println("Read object
" + o);
|
|
|
|
Object o2 = ois.readObject();
|
|
Student[] s = (Student[])o2;
|
|
System.out.println(s[0]);
|
|
System.out.println(s[1]);
|
|
System.out.println(s[0] == s[1]);
|
|
System.out.println(s[0] == o);
|
|
}
|
|
finally {
|
|
try {ois.close();} catch (IOException
ioe) {}
|
|
}
|
|
}
|
|
}
|