首页 > 代码库 > IO流中ObjectOutputStream和ObjectInputStream的使用
IO流中ObjectOutputStream和ObjectInputStream的使用
package ObjectIntOutputStreamDemo; import java.io.Serializable;//注意每个类都要有这个接口 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,"涂鹏"); Student s2=new Student(1002,"曾涛"); Teacher t1=new Teacher(10003, "石臻臻", "软件学院"); Teacher t2=new Teacher(10004, "石石石", "软件学院"); 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());//对比一下 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()); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。