English 中文(简体)
如何使用ObjectOutputStream和ObjectInputStream
原标题:How to use ObjectOutputStream and ObjectInputStream

细节:

我的课程是一本包含5个班级的成绩单,这些班级都是汇总的。成绩册有课程,课程有类别,类别有成绩(所有数组列表)。我的程序还有一个StateManager,其唯一目的是由于深度聚合而返回对对象的引用。在我的驱动程序中,我没有创建成绩册的实例,而是创建了一个状态管理器,它有一个成绩册的静态实例,并带有返回引用的方法。

我的目标是保存所有这些数据,以便在程序重新运行时重新打开。

问题:

当我写文件时,我需要做的就是写StateManager对象,对吗?我想我甚至已经做到了这一点。我让程序创建一个“gradebook.data”文件。有没有一种方法可以在文本程序中打开.data文件,看看它是否正确写入?

我在哪里用inputstream再次打开对象?在静态main方法中还是在初始化所有图形的方法的开头?

谢谢

最佳回答

序列化StateManager不会做任何事情,因为您有一个静态GradeBook实例字段会被序列化。因此,删除静态限定符。您可以将StateManager本身设置为单例,并对其进行静态

然而,我仍然怀疑你为什么不序列化GradeBook实例。这将是一种更合乎逻辑的方法。我们通常不序列化服务对象,而是序列化数据对象,而您已经实现了这种分离。

问题回答

在首次使用之前,您需要在程序的“早期”某个地方读取数据。在StateManager的初始化代码中,可能有一个位置。

我不明白为什么“初始化所有图形的方法”是一个合乎逻辑的地方。

不,没有文本编辑器会以正确的文本格式显示所有细节,因为你写的是字节,你的文本编辑器希望你提供文本。

将对象从磁盘加载到内存-两种方法

  1. 提前加载它们,在main方法中加载它们的意义上,如果你不使用它们,你从磁盘加载它们的努力就白费了,你使用了内存和CPU,但没有进一步使用。

  2. 当您第一次访问它们时加载它们,称为延迟加载,因此当您访问StateManager的静态方法时,如果您的对象为null,您将从磁盘加载它们。

离题:

A这是一篇很好的文章,详细解释了序列化。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...