如何实现序列化?

How to implement Serializable?

我应该如何implement Serializable 界面?

我有一个 class Student,需要能够将它保存到磁盘。对于我的家庭作业,我必须序列化五个不同的 Student 对象并将它们保存到文件中。

class Student {
     String mFirstName;
     String mSecondName;
     String mPhoneNumber;
     String mAddress;
     String mCity;

Student(final String pFirstName, final String pSecondName, final String pPhoneNumber, final String pAddress, final String pCity){
    this.mFirstName = pFirstName;
    this.mSecondName = pSecondName;
    this.mPhoneNumber = pPhoneNumber;
    this.mAddress = pAddress;
    this.mCity = pCity;

}}

我试过使用 ObjectOutputStream 序列化一个 Student,但它抛出一个错误:

ObjectOutputStream lOutputStream = new ObjectOutputStream(new FileOutputStream("file.txt", true));
lOutputStream.write(new Student("foo","bar","555-1234","Flat 40","Liverpool"));

您唯一需要做的就是实现 Serializable。实现这个接口时你唯一需要担心的是确保 class 的所有字段也实现了 Serializable 接口。在您的情况下,所有字段都是字符串,并且它们已经实现了可序列化。因此,你只需要添加implements Serializablehttps://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/Serializable.html

public class Student implements Serializable {
    String first;
    String second;
    String phone;
    String cityAddress;
    String cityStreet;

    public Student(String s1, String s2, String s3, String s4, String s5) {
        first = s1;
        second = s2;
        phone = s3;
        cityAddress = s4;
        cityStreet = s5;
    }
}