JAVA 类序列化中的问题
package Iodemo; import java.io.*; public class ObjectInputStreamDemo { public static void main(String[] args) throws IOException, ClassNotFoundException { write(); read(); } public static void read() throws IOException, ClassNotFoundException { ObjectInputStream obs = new ObjectInputStream(new FileInputStream("./1.txt")); Object o = obs.readObject(); Student s = (Student) o; System.out.println(s.getName()+"||"+s.getAge()); } public static void write() throws IOException { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("./1.txt")); Student s = new Student("张三",20); oos.writeObject(s); oos.close(); } }
需要注意 如果是序列化类 最好设置序列化的版本ID这样就不出现修改类文件后 出现版本不一致异常,对于不想序列化的元素 我们可以通过transient 关键字修饰