在java.io包中,接口Serializable用来作为实现对象串行化的工具,只有实现了Serializable的类的对象才可以被串行化。串行化的对象可以将状态保存
到硬盘上。
定义一个串行化的对象
public class Student implements Serializable{
int id; //学号
String name; //姓名
int  age; //年龄
String department //系别
public Student(int id,String name,int age,String department){
this.id = id;
this.name = name;
this.age = age;
this.department = department;
}

保存对象状态
Student stu=new Student(981036,”Liu Ming”,18, “CSD”);
FileOutputStream fo
=new FileOutputStream("data.ser");
ObjectOutputStream so
=new ObjectOutputStream(fo);
try{
   so.writeObject(stu); so.close();
  }catch(IOExceptione )
{System.out.println(e);}
恢复对象状态
FileInputStream fi
=new FileInputStream("data.ser");
 ObjectInputStream si
=new ObjectInputStream(fi);
 try{
stu=(Student)si.readObject();
si.close();
}catch(IOExceptione )
   {System.out.println(e);}串行化只能保存对象的非静态成员变量,不能保存任何的成员方法和静态的成员变量,而且串行化保存的只是变量的值,对于变量的任何修饰符,都不能保存。对于某些类型的对象,其状态是瞬时的,这样的对象是无法保存其状态的,例如一个Thread对象,或一个FileInputStream对象,对于这些字段,必须用transient关键字标明。
对象串行化首先写入类数据和类字段的信息,然后按照名称的上升排列顺序写入其数值。如果想自己明确地控制这些数值的写入顺序和写入种类,必须定义自己的读取数据流的方式。就是在类的定义中重写writeObject()和readObject()方法。