java 使用序列化写出或者读取对象

进行写出前,建议在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();
}
}
}

 

posted @ 2022-11-06 21:48  黄大虾  阅读(80)  评论(0编辑  收藏  举报