import java.io.*;
class Person implements Serializable
{
public static final long serialVersionUID = 42L;
private String name;
transient int age;
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;
}
}
这里有几个需要注意的地方:
(1)静态变量不被序列化:static String country = “cn”;
(2)加上transient的变量不被序列化;
(3)编译时候系统会自动计算序列化的一个标识码,为了不让每次修改一点对象就序列化不了,我门可以使用public static final long serialVersionUID = 42L;
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();
}
}
ObjectInputStream和ObjectOutputStream是相对应的。
readObject和writeObject是相对应的。