对要序列化的文件需要实现Serializable接口,这个接口是一个标签,虽然没有任何抽象方法。
常量serialVersionUID 设置为一个任意值,保证在Student类改变时,原先存在的student可读
实现序列化和反序列化的Test类中代码
package com.oop.next.test0305;
import java.io.*;
public class Student extends Person implements Serializable {
private Integer stuId;
private transient String addresss;
private static final long serialVersionUID = 1212;
public Student( String stuName, String stuSex,Integer stuId, String addresss) {
super(stuName, stuSex);
this.stuId = stuId;
this.addresss = addresss;
}
@Override
public String toString() {
return "Student{" +
"stuId=" + stuId +
", addresss='" + addresss + '\'' +
'}';
}
}
class Person{
private String stuName;
private String stuSex;
public Person(String stuName, String stuSex) {
this.stuName = stuName;
this.stuSex = stuSex;
}
public Person() {
}
}
class Test{
public static void main(String[] args) {
//
Student s = new Student("rk","s",1,"adad");
try(
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("e:\\dnf怀旧\\stu.db"));
) {
// File fileInputStream = new File("e:\\dnf怀旧\\stu.db");
// fileInputStream.createNewFile();
objectOutputStream.writeObject(s);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try(
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("e:\\dnf怀旧\\stu.db"));
){
Student read = (Student)objectInputStream.readObject();
System.out.println(read);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}