对象的序列化指将一个java对象写入io流中,与此对应的反序列化则是指从io流中恢复该java对象.如果需要让某个对象可以支持序列化,必须让它的类是可序列化的,即必须实现如下两个接口之一:
1 Serializable
2 Externalizable
例如:
import java.io.Serializable;
public class Person implements Serializable
{
private String name = null;
private int age = 0;
public Person(String name,int age)
{
this.name = name;
this.age = age;
}
public int getAge()
{
return age;
}
}
import java.io.*;
public class TestSerializable
{
public static void main(String[] args)
{
ObjectOutputStream oos = null;
ObjectInputStream ois=null;
try
{
oos = new ObjectOutputStream(new FileOutputStream("textperson.txt"));
Person p = new Person("孙悟空",20);
oos.writeObject(p);
oos.close();
ois = new ObjectInputStream(new FileInputStream("textperson.txt"));
Person per = (Person) ois.readObject();
System.out.println(per.getAge());
ois.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
catch(ClassNotFoundException cfe)
{
cfe.printStackTrace();
}
}
}
[ 本帖最后由 包志恒 于 2011-07-23 18:15 编辑 ] |