一 序列化对象类
import java.io.Serializable;
public class Person implements Serializable
{ // 此类的对象可以被序列化
public static final long serialVersionUID = 42L;
private String name; // 声明name属性
private int age; // 声明age属性
String country = "cn";
public Person(String name, int age ,String country)
{ // 通过构造方法设置属性内容
this.name = name;
this.age = age;
this.country = country;
}
public String toString()
{ // 覆写toString()方法
return "姓名:" + this.name + ";年龄:"
+ this.age + ";国籍:" + this.country;
}
}
二 测试类
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class SerDemo01
{
public static void main(String[] args) throws Exception
{
File f = new File("SerTest.txt");
ObjectOutputStream oos = null;
OutputStream out = new FileOutputStream(f); // 文件输出流
oos = new ObjectOutputStream(out); // 为对象输出流实例化
oos.writeObject(new Person("Tom", 25, "America")); // 保存对象到文件
oos.close(); // 关闭输出
}
}
三 运行