进行写出前,建议在pojo类中,定义属性“serialVersionUID“ ,否则对象以后要更改或添加属性时,再读取原来的文件会报错
例如下面实体类
public class Ren implements Serializable {
//序列化最好定义此属性 private final static long serialVersionUID = 1L; private String name; private int age; private Date birthDay;
get和set 构造方法。。。。
}
测试写出和读取
public class Tets {
public static void main(String[] args) {
Ren ren1 = new Ren("黄大侠", 16, new Date(),"抽烟");
try {
//序列化写出到文件
// ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("D:\\testObj"));
// objectOutputStream.writeObject(ren1);
// objectOutputStream.close();
//序列化读取到文件
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D:\\testObj"));
Ren ren2 = (Ren) objectInputStream.readObject();
ren2.toString();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
标签:java,读取,private,写出,Ren,new,序列化 From: https://www.cnblogs.com/huangruiwu/p/16864253.html