写入Student对象到Student.txt
public class WriterStudent {
public static void main(String[] args) {
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Student.txt"));
Student stu1 = new Student("徐恺",19);
Student stu2 = new Student("路娟娟",18);
Student stu3 = new Student("崔亚涛",20);
oos.writeObject(stu1);
oos.writeObject(stu2);
oos.writeObject(stu3);
//写入结束标志方便读取(非常重要,如果不写入,在读取的时候无法定位读取结束);
oos.writeObject(null);
oos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
读取Student对象到console
public class ReaderStudent {
public static void main(String[] args) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("Student.txt"));
try {
Student s = null;
while(true){
if((s = (Student)ois.readObject()) != null){
s.showInfo();
}else{
break;
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
序列化Student类
package com.lanou3g.job11;
import java.io.Serializable;
public class Student implements Serializable{
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void showInfo(){
System.out.println("姓名:" + name + ",年龄" + age);
}
}