这个方法用在复杂的对象中时非常好用, 如把一个JTree的对象写入文件, 然后再直接从文件读出,然后直接使用,出现的还是上次操作的状态,如果自己去做这个工作, 会非常的困难。
import java.io.*;
// 在Java中系列化很简单, 只要实现一个无函数的接口Serializable即可。
public class Student implements Serializable {
private static final long serialVersionUID = -6670528088216041285L;
private String name;
private int ID;
public Student(String name, int ID) {
this.name = name;
this.ID = ID;
}
public String getName() {
return name;
}
public int getID() {
return ID;
}
public static void main(String[] agrs) {
// 先产生几个学生的对象
Student st1 = new Student("Google", 100);
Student st2 = new Student("Baidu", 101);
Student st3 = new Student("Yahoo", 102);
// 把对象写入文件.
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("data.txt"));
oos.writeObject(st1);
oos.writeObject(st2);
oos.writeObject(st3);
st1 = null;
st2 = null;
st3 = null;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
oos = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 把对象从文件读入.
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("data.txt"));
st3 = (Student) ois.readObject();
st2 = (Student) ois.readObject();
st1 = (Student) ois.readObject();
// 输出从文件中读取到的学生的信息, 用于查检是否正确
System.out.println(st1.getName() + "'s ID is " + st1.getID());
System.out.println(st2.getName() + "'s ID is " + st2.getID());
System.out.println(st3.getName() + "'s ID is " + st3.getID());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
ois = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}