本帖最后由 顾传文 于 2013-3-12 09:14 编辑
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class Test { public static void main(String[] args) throws Exception{ writerObj(); readObj(); } //将堆内存中的Perosn对象保存到文件中 public static void writerObj() throws Exception{ ObjectOutputStream objectOutputStream = new ObjectOutputStream( new FileOutputStream("c:\\persons.object")); objectOutputStream.writeObject(new Person("guchuanwen",25,"chinese")); } //将文件中的内容读到堆内存中。 public static void readObj() throws Exception{ ObjectInputStream objectInputStream = new ObjectInputStream( new FileInputStream("c:\\persons.object")); Person person = (Person)objectInputStream.readObject(); System.out.println(person); } } /** * Serializable接口没有需要实现方法, * 没有实现方法的接口为标记接口。 */ class Person implements Serializable{ //serialVersionUID的访问修饰符没有要求,可以为public,private... public static final long serialVersionUID = 42L; private String name; private transient Integer age; static String country ="cn"; public Person(String name,Integer age,String country){ this.name = name; this.age = age; this.country = country; } public String toString(){ return name+":"+age+":"+country; } }
打印结果:guchuanwen:null:chinese
怎么我这里的county读出来不是cn而是Chinese呢?static类型的字段不是不被序列化的吗? |