import java.io.Serializable;
/**
* 首先定义一个Person类,负责存储员工的姓名name,岗位job,年龄age
* 然后序列化这个类写入文档。在需要的时候反序列化读取。
*
*/
public class Person implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String job;
private int age;
public Person() {
super();
}
public Person(String name, String job, int age) {
super();
this.name = name;
this.job = job;
this.age = age;
}
@Override
public String toString() {
return "名字:" + name + "岗位:" + job + "年龄" + age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* 这是一个测试序列化与反序列化的Demo类,叫做TestSerializabeDemo类;
*
*
*/
public class TestSerializabeDemo {
public static void main(String[] args) throws FileNotFoundException,IOException, ClassNotFoundException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:/MyPerson.txt", true));
oos.writeObject(new Person("张三", "coder", 30));
oos.writeObject(new Person("李四", "acount", 40));
oos.writeObject(new Person("王五", "boss", 50));
oos.writeObject(null);
oos.flush();
oos.close();
System.out.println("对象序列化写入完毕。");
System.out.println("下面开始反序列化读取对象。");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:/MyPerson.txt"));
Person p = (Person) ois.readObject();
try {
while (p != null) {
System.out.println(p);
p = (Person) ois.readObject();
}
} catch (EOFException e) {
System.out.println("如果序列化写入时,最后不写入一个null,则会抛这个EOFException异常");
}
ois.close();
System.out.println("反序列化读取完成。");
}
}