Package objectintoutputstreamdemo; import Java. io. serializable; // note that each class must have this interface public class student implements serializable {private int ID; Public student (int id, string name) {super (); this. id = ID; this. name = Name;} public int GETID () {return ID;} public void setid (int id) {This. id = ID;} Public String getname () {return name;} public void setname (string name) {This. name = Name;} private string name; Public student () {// todo auto-generated constructor stub }}
package ObjectIntOutputStreamDemo;import java.io.Serializable;public class Teacher implements Serializable {public int getTeacherId() {return teacherId;}public void setTeacherId(int teacherId) {this.teacherId = teacherId;}public String getTeacherName() {return teacherName;}public void setTeacherName(String teacherName) {this.teacherName = teacherName;}public String getDepartment() {return department;}public void setDepartment(String department) {this.department = department;}private int teacherId;private String teacherName;private String department;public Teacher() {// TODO Auto-generated constructor stub}public Teacher(int teacherId, String teacherName, String department) {super();this.teacherId = teacherId;this.teacherName = teacherName;this.department = department;}}
Package objectintoutputstreamdemo; import Java. io. fileinputstream; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. objectinputstream; import Java. io. objectoutputstream; import Java. io. serializable; public class objectdemo implements serializable {/*** @ Param ARGs * @ throws ioexception * @ throws classnotfoundexception */public static void main (string [] ARGs) throws ioexception, classnotfoundexception {student S1 = new student (1001, "tu peng"); Student S2 = new student (1002, "Zeng Tao"); teacher T1 = new teacher (10003, "Shi Zhen", "Software Institute"); teacher t2 = new teacher (10004, "Shi", "Software Institute"); fileoutputstream out = new fileoutputstream (". // student.txt "); objectoutputstream oout = new objectoutputstream (out); oout. writeobject (S1); oout. writeobject (S2); oout. writeobject (T1); oout. writeobject (T2); fileinputstream in = new fileinputstream (". // student.txt "); objectinputstream oin = new objectinputstream (in); Student S3 = (student) oin. readobject (); Student S4 = (student) oin. readobject (); teacher T3 = (teacher) oin. readobject (); teacher t4 = (teacher) oin. readobject (); oin. close (); system. out. println (s1.getid () + "" + s1.getname (); // compare system. out. println (s3.getid () + "" + s3.getname (); system. out. println (t1.getteacherid () + "" + t1.getteachername () + "" + t1.getdepartment (); system. out. println (t3.getteacherid () + "" + t3.getteachername () + "" + t3.getdepartment ());}}