Serializable与Externalizable详解

1. Serializable自动序列化
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person implements Serializable {
    private int age;
    private String username;
}

public static void main(String[] args) throws Exception {
    // Person已经实现序列化接口 Serializable
    Person person = new Person();
    person.setAge(18);
    person.setUsername("tom");

    File targetFile = new File("/Users/jack/Java/JavaDemo/temp.txt");

    // 序列化person对象到temp.txt中
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(targetFile));
    objectOutputStream.writeObject(person);
    objectOutputStream.flush();
    objectOutputStream.close();

    // 反序列化person对象
    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(targetFile));
    Person newPerson = (Person) objectInputStream.readObject();
    objectInputStream.close();
    System.out.println(newPerson);
}
程序打印结果:Person(age=18, username=tom
2. Externalizable手动序列化(选择你想要序列化的属性)
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class OtherPerson implements Externalizable {

    private int age;
    private String username;

    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(age);
        out.writeObject(username);
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        this.age = in.readInt();
        this.username = (String) in.readObject();
    }
}

public static void main(String[] args) throws Exception {
    // OtherPerson已经实现序列化接口Externalizable
    OtherPerson person = new OtherPerson();
    person.setAge(18);
    person.setUsername("tom");

    File targetFile = new File("/Users/jack/Java/JavaDemo/temp2.txt");

    // 序列化OtherPerson对象到temp2.txt中
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(targetFile));
    objectOutputStream.writeObject(person);
    objectOutputStream.flush();
    objectOutputStream.close();

    // 反序列化OtherPerson对象
    ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(targetFile));
    OtherPerson newPerson = (OtherPerson) objectInputStream.readObject();
    objectInputStream.close();
    System.out.println(newPerson);
}
输出结果:OtherPerson(age=18, username=tom)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容