//Student.java
import java.io.*;
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;
}
//一般可不重写,定制串行化时需要重写writeObject()方法
private void writeObject(ObjectOutputStream out)throws IOException
{
out.writeInt(id);
out.writeInt(age);
out.writeUTF(name);
out.writeUTF(department);
}
//一般可不重写,定制串行化时需要重写readObject()方法
private void readObject(ObjectInputStream in)throws IOException
{
id=in.readInt();
age=in.readInt();
name=in.readUTF();
department=in.readUTF();
}
}//Objectser.java
import java.io.*;
public class Objectser
{
public static void main(String args[])throws IOException,ClassNotFoundException
{//stu对象与ObjectOutputStream联系起来
Student stu=new Student(20001001,"LiuMing",20,"CSD");
FileOutputStream fout=new FileOutputStream("data.ser");
ObjectOutputStream sout=new ObjectOutputStream(fout);
try
{
sout.writeObject(stu);
sout.close();
}
catch(IOException e)
{
System.out.println(e);
}
stu=null;
//stu对象与ObjectInputStream类型起来
FileInputStream fin=new FileInputStream("date.ser");
ObjectInputStream sin=new ObjectInputStream(fin);
try
{//输入流对象状态从文"date.ser"读出
    stu=(Student)sin.readObject();
    sin.close();
}
catch(IOException e)
{
System.out.println(e);
}
System.out.println("Student info:");
System.out.println("ID :"+stu.id);
System.out.println("Name:"+stu.name);
System.out.println("Age :"+stu.age);
System.out.println("Dep.:"+stu.department);
}
}