import java.io.*;
public 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.*;
public class Person implements Serializable{
public static final long serialVersionUID = 42L;
static String country="cn";
transient private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
Person(String name,int age,String country)
{
this.name=name;
this.age=age;
this.country=country;
}
public String toString()
{
return name+":"+age+":"+country;
}
}
上面的代码,如果writeObj();方法和readObj();方法一起执行,则结果输出lisi0:0:kr;两个方法分开执行则会输出lisi0:0:cn。
这是为什么?
|
|