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)

你可能感兴趣的:(Serializable与Externalizable详解)