import java.io.*;
class ObjectStreamDemo
{
public static void main(String[] args) throws Exception
{
//wrtieObj();
readObj();
}
public static void wrtieObj() throws IOException
{
ObjectOutputStream oos=
new ObjectOutputStream (new FileOutputStream("obj.txt"));
oos.writeObject(new Person("lisi",39));
oos.close();
}
//读取一个对象
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();
}
}
class Person implements Serializable
{
public static final long serialVersionUID=42L;
private String name;
static String country="cn";//静态不能被序列化,他在方法区
transient int age;//非静态的不想被序列化就前面加 transient
Person(String name,int age,String country)
{
this.name=name;
this.age=age;
}
public String toString()
{
return name+":"+age+":"+country;
}
} |
|