首页 > 代码库 > 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());
	}

}