我百度到的题目,我运行试了一下,也看不懂结果为什么?
第一种情况:先把readObj()注释掉,写入以后,再先把writer注释掉,然后再把readObj方法打开
writeObj();
//readObj();
然后再
//writeObj();
readObj();
输出结果:lisi--0--CN
第二种情况:两个都不注释同时运行
writeObj();
readObj();
输出结果:lisi--0--KR
输出结果为啥不一样???
第二种情况下,statci的 country 属性咋就变了呢
- package io.inputoutput;
- import java.io.*;
- class Person implements Serializable {
- public static final long serialVersionUID = 42L;
- 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;
- }
- }
- public class ObjStream01 {
- public static void main(String[] args) throws IOException,
- ClassNotFoundException {
- writeObj();
- readObj();
- }
- public static void writeObj() throws IOException { // 写入对象
- ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
- "F:\\A\\123.txt"));
- oos.writeObject(new Person("lisi", 19, "KR"));
- oos.close();
- }
- public static void readObj() throws IOException, ClassNotFoundException { // 读取对象
- ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
- "F:\\A\\123.txt"));
- Person p = (Person) ois.readObject();
- System.out.println(p);
- ois.close();
- }
- }
复制代码 |