user
user

Reputation: 6807

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 example?
(The elements in the Collection are custom classes. Do I need to implement a method that serializes the objects?)

Upvotes: 1

Views: 2459

Answers (3)

Andreas
Andreas

Reputation: 5335

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.

Upvotes: 0

Tony Ennis
Tony Ennis

Reputation: 12309

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.

Upvotes: 0

Nuwan
Nuwan

Reputation: 177

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.

Upvotes: 1

Related Questions