如何实现可序列化?

编程入门 行业动态 更新时间:2024-10-10 21:25:08
本文介绍了如何实现可序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我应该如何实现 可序列化界面?

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

I have a class Student, and need to be able to save it to disk. For my homework, I have to serialize five different Student objects and save them to file.

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 ,但是会引发错误:

I've tried using ObjectOutputStream to serialize a Student, but it throws an error:

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

推荐答案

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

The only thing you need to do is implement Serializable. The only thing you need to worry when implementing this interface is to make sure that all fields of such class, has implemented Serializable interface as well. In your case all fields are Strings and they already implement Serializable. Therefore, you only need to add implements Serializable. docs.oracle/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; } }

更多推荐

如何实现可序列化?

本文发布于:2023-11-25 09:17:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629189.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何实现   序列化

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!