200_IO流_序列化版本号_serialVersionUID详解

时间:2022-05-07 21:36:56
import java.io.Serializable;

//因为User实现了Serializable 接口。JVM会特殊待遇,会给该类添加一个属性
// static final long serialVersionUID = -5777248435420590281L
public class User implements Serializable {

//不让系统自动生成,自己写一个序列化版本号
private static final long serialVersionUID = -5777248435420590281L;
String name;
//如果不想让该属性参加序列化,需要使用transient关键字
transient int age;
public User(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
 
 
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;public class Test {public static void main(String[] args) throws Exception {ObjectOutputStream  oos = new ObjectOutputStream(new FileOutputStream("bin/temp01"));User u1 = new User("张三",20);User u2 = new User("李四",30);oos.writeObject(u1);oos.writeObject(u2);oos.close();ObjectInputStream ois  = new ObjectInputStream(new FileInputStream("bin/temp01"));Object obs = ois.readObject();Object obs1 = ois.readObject();System.out.println(obs);System.out.println(obs1);ois.close();}}