import java.io.*;
class ObjectStreamDemo
{
public static void main(String[] args) throws Exception
{
//writeObj();
readObj();
}
public static void readObj()throws Exception
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));
Person p = (Person)ois.readObject();
System.out.println(p);
ois.close();
}
public static void writeObj()throws IOException
{
ObjectOutputStream oos =
new ObjectOutputStream(new FileOutputStream("obj.txt"));
oos.writeObject(new Person("lisi0",399,"kr"));
oos.close();
}
}
import java.io.*;
class Person implements Serializable //继承Serializable(没有方法 称为标记接口 为类提供一个UID号 用于区分)
{
public static final long serialVersionUID = 42L;//用此方法固定一个UID 即使改变此类也可以继续读取
private String name;//序列化堆内存中的内容
transient int age;//不是静态想不被序列化 用transient修饰
static String country = "cn";//静态存在于方法区中 不会被序列化
Person(String name,int age,String country)
{
this.name = name;
this.age = age;
this.country = country;
}
public String toString()
{
return name+":"+age+":"+country;
}
}