使用 Java 中的序列化将对象保存到文件
我在集合
中存储了大量数据。
我想将此数据保存到文件中。使用序列化是个好主意吗?
或者我应该使用自定义格式来保存数据,或者将其保存为 XML 等?
(Collection
中的元素是自定义类。我需要实现序列化对象的方法吗?)
I have a large amount of data stored in a Collection
.
I would like to save this data to a file. Is it a good idea to use Serialization?
Or should I use a custom format to save the data, or save it as XML for example?
(The elements in the Collection
are custom classes. Do I need to implement a method that serializes the objects?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用这两种方法。我更愿意将它们保存为 XML,因为 XML 文件中数据损坏的可能性较小。
但是,如果您想使用序列化将自定义类保存到数据文件中,则需要在这些自定义类中实现 Serialized 接口。
You can use both methods. I would prefer to save them as XML, because it is less likely to have a data corruption in XML file.
But if you want to save custom class into data file using serialization you need to implement Serializable interface in those custom classes.
我不会将序列化的类写入磁盘。一旦 JVM 或任何库发生变化,它可能就没用了。这意味着在一个系统上创建的文件可能无法在另一个系统上工作!
相反,我会编写数据的文本版本。如果您的集合包含其他集合或类,我会使用 XML,因为它可以很好地处理嵌套。如果数据很简单,我可能只编写一个逗号分隔文件,其标题行包括版本号和数据集的描述,一行告诉列名,数据行和 EOF 行。
I would not write a serialized class to disk. Once the JVM or any libraries change it might be useless. This means a file created on one system may not work on another!
Instead, I'd write a text version of the data. If your collection includes other collections or classes, I'd use XML as it handles nesting well. If the data is simple I'd probably just write a comma-sep file with a header line including a version number and a description of the data set, a line telling the column names, the data lines, and an EOF line.
我需要实现序列化对象的方法吗?
为了序列化对象,您应该实现 Serialized 接口或者如果在序列化和反序列化过程中需要“特殊”处理,则提供以下方法的实现。
您可以在 oracle 站点上找到有关序列化的更多详细信息。您可以访问 http://java.sun.com/developer/technicalArticles/Programming/serialization / 开始。
Do I need to implement a method that serializes the objects?
In order to serialize an object you should implement the Serializable interface OR provide the implementation for the following methods IF a 'special'handling during the serialization and deserialization process is required.
You can find more details on serialization on the oracle site. You can visit http://java.sun.com/developer/technicalArticles/Programming/serialization/ to get started.