FileOutputStream outFile = new FileOutputStream(“temp.txt”); ObjectOutputStream out = new ObjectOutputStream (outFile);
反序列化的步骤?
FileInputStream inFile = new FileInputStream("temp.txt"); ObjectInputStream in= new ObjectInputStream (inFile);
例子:
//一个学生对象
class Student implements Serializable {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
}
…
ObjectOutputStream out = new ObjectOutputStream
(new FileOutputStream("e:\\objectFile.txt"));
//序列化对象
Student stu = new Student("成龙", 50);
out.writeObject(stu);
out.close();
//反序列化对象
ObjectInputStream in = new ObjectInputStream
(new FileInputStream("e:\\objectFile.txt"));
Student stu1 = (Student) in.readObject();
System.out.println(stu1); //关闭流
in.close();
实现序列化对象和反序列化对象的类是什么 ?
ObjectInputStream和ObjectOutputStream
每个类的对象在序列化的时候,JAVA虚拟机会自动根据类中的属性和方法计算出一个序列化版本号。(也就是说:如果类中的属性和方法改变了,那么算出的版本号也会改变)。当反序列化时,JAVA虚拟机会判断流中的对象的序列化版本号与你的类的版本号是否一致,如果不一致,会发生 InvalidClassException 无效的类异常。