importjava.io.ObjectOutputStream;importjava.io.IOException;importjava.io.FileOutputStream;importjava.io.FileInputStream;importjava.io.ObjectInputStream;classObjectStreamD...
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
class ObjectStreamDemo{
public static void writeObj()throws IOException{
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("Person.txt"));//创建写入指定 OutputStream 的 ObjectOutputStream。
//此构造方法将序列化流部分写入底层流
oos.writeObject(new Person("zhang",12,"haha"));//将指定的对象写入 ObjectOutputStream
/*
对象的类、类的签名(SerialVersionUID),以及类及其所有父类的非瞬态和非静态字段的值都将被写入
*/
oos.close();
}
public static void readObj()throws IOException,ClassNotFoundException{
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("Person.txt"));//创建从指定 InputStream 读取的 ObjectInputStream。
Person p=(Person)ois.readObject();//将读取流中的一个对象返回,当有多个对象可以采用循环读取
//注意该方法上声明两个异常(IOException,ClassNotFoundException)
System.out.println(p.toString());
}
public static void main(String[] args)throws IOException,ClassNotFoundException{
writeObj();
readObj();
}
}
import java.io.Serializable;
public class Person implements Serializable{
private static final long serialVersionUID=100L;
private String name;
int age;
private static String country="cn";
public Person(String name,int age,String country){
this.name=name;
this.age=age;
this.country=country;//非静态可以访问静态
}
public String toString(){
return name+"..."+age+"..."+country;
}
}
问题就是:结果是 zhang...12...haha
但是如果:
先writeObj(),然后readObj()
结果zhang...12...cn (这个是正确的)
麻烦大神门详细解释下,出现上述情况的原因.
展开