package com.hspedu.io_; import org.junit.Test; import java.io.*; public class SerializableObject_ { @Test public void serializableObjectDetails() throws IOException { String path = "e:\\JavaIO\\SerializableTest\\test.txt"; ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(path)); Human zh = new Human("张三", 10, "中国", "黄皮肤"); objectOutputStream.writeObject(zh); objectOutputStream.close(); } @Test public void deserializableDetails() throws IOException, ClassNotFoundException { String path = "e:\\JavaIO\\SerializableTest\\test.txt"; ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(path)); Object zh = objectInputStream.readObject(); System.out.println(zh); } } class Human implements Serializable { private String name; private int age; private static String nation; // static不具备序列化 private transient String skipColor; // transient不具备序列化 private Chinese chinese = new Chinese(); private static final long serialVersionUID = 1L; // serialVersionUID判断序列化版本一致性,序列化和反序列化必须一致 public Human(String name, int age, String nation, String skipColor) { this.name = name; this.age = age; this.nation = nation; this.skipColor = skipColor; } @Override public String toString() { return name + ", " + age + ", " + nation + ", " + skipColor + ", " + chinese; } } class Chinese implements Serializable { @Override public String toString() { return "Chinese{}"; } }
注意:1、序列化和反序列化的类必须实现(implements) Serializable接口;
2、序列化和反序列化的顺序必须一致;
3、兼容性:一般添加 private static final long serialVersionUID = xxxL; 属性
序列化和反序列化serialVersionUID的值前后必须一致
参考博客:https://blog.csdn.net/u014750606/article/details/80040130