开发者

Saving object to file using Serialization in Java

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 examp开发者_JAVA百科le?

(The elements in the Collection are custom classes. Do I need to implement a method that serializes the objects?)


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.


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.


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.

- private void writeObject(ObjectOutputStream out) throws IOException;
- private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜