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已經(jīng)實現(xiàn)序列化接口 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);
}
程序打印結(jié)果: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已經(jīng)實現(xiàn)序列化接口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);
}
輸出結(jié)果:OtherPerson(age=18, username=tom)