本帖最后由 张其辉 于 2012-10-24 15:45 编辑
import java.io.*;
public class io3 {
public static void main(String[] args) throws Exception
{
writeObj();
readObj();
}
public static void readObj()throws Exception//读取序列化后的文件obj.txt
{
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//输出经过序列化的文件,存储在obj.txt中
{
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("obj.txt"));
oos.writeObject(new Person("lisi", 32,"kr"));//注意这一句country输入的是kr
oos.close();
}
}
class Person implements Serializable
{
public static final long serialVersionUID=42L;
String name;
int age;
static String country="cn";//注意这里定义的是cn
Person(String name,int age,String country)
{
this.name=name;
this.age=age;
this.country=country;
}
public String toString()
{
return name+":"+age+":"+country;
}
}上面红色的两句,如果注释掉readObj();单独运行writeObj();然后再运行readObj();结果为lisi:32:cn
如果writeObj();和readObj();都不注释掉,同时存在,运行结果为 isi:32:kr
为什么两次结果不一样呢?
|