import java.io.*;
import java.io.Serializable;
/**
*
* <p>Title: 对象序列化</p>
* <p>Description:
*
1.并非所有类都可以序列化。在命令窗口下,可以通过serialver命令来检查一个类是否可以序列化。如输入serialver java.net.Socket,可以得到socket是否可序列化的信息,实际上socket是不可序列化的。
2.java有很多基础类已经实现了serializable接口,如String,Vector等。
3.如果某个类能够被序列化,其子类也可以被序列化。
4.声明为static和transient类型的成员数据不能被序列化。因为static代表类的状态, transient代表对象的临时数据。
5.读取序列化对象时,不会调用对象的任何构造函数甚至default构造函数,整个对象的状态全是通过InputStream所读的数据回复。
</p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
class Student implements Serializable {
private String sNO;
private String sName;
private String sSpecial;
private int iAge;
Student(String sNO, String sName, int iAge, String sSpecial) {
this.sNO = sNO;
this.sName = sName;
this.sSpecial = sSpecial;
this.iAge = iAge;
}
}
public class Serial {
public static void main(String[] args) throws IOException,
ClassNotFoundException, IOException {
/**
*写文件
*/
ObjectOutputStream ojectOut = new ObjectOutputStream(new FileOutputStream(
"c:/student.dat"));
Student student1 = new Student("S200106001", "李铭", 21, "经济管理");
Student student2 = new Student("S200105001", "郝丽", 22, "外语");
ojectOut.writeObject(student1);
ojectOut.writeObject(student2);
ojectOut.close();
/**
* 读文件
*/
ObjectInputStream objectIn = new ObjectInputStream(new FileInputStream("c:/student.dat"));
Student s1 = (Student)objectIn.readObject();
Student s2 = (Student)objectIn.readObject();
objectIn.close();
System.out.println(s1);
System.out.println(s2);
}
}