如何实现可序列化?

2022-09-02 12:29:10

我应该如何界面?implementSerializable

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

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;

}}

我尝试使用 来序列化一个 ,但它抛出了一个错误:ObjectOutputStreamStudent

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

答案 1

您唯一需要做的就是实现可序列化。实现此接口时唯一需要担心的是确保此类的所有字段也已实现可序列化接口。在你的例子中,所有字段都是字符串,它们已经实现了可序列化。因此,您只需要添加可序列化的实现https://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;
    }
}

答案 2