Browse DevX
Sign up for e-mail newsletters from DevX


Implement Persistent Objects with Java Serialization : Page 2

One of the most critical operations an application can perform is saving and restoring its state between successive runs. Yet, saving data in a textual format is not always practical--or secure. Using serialization, you can save any Java object to disk in a flash.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Serializing Objects
Java makes serializing objects easy. You can make any object whose class implements the java.io.Serializable interface persistent with only a few lines of code. Unlike implementing the ActionListener event-handling interface, for example, no extra methods need to be added to implement the interface—the purpose of the interface is simply to identify which classes can be safely serialized and which cannot at runtime. You need only add the implements keyword to your class declaration to identify your classes as serializable, like so:

public class UserData implements java.io.Serializable

Once a class is serializable, you can write the object to any OutputStream, such as to disk. To achieve this, you must first create an instance of java.io.ObjectOutputStream and pass the constructor an existing OutputStream instance. You could use code like this:

// Use a FileOutputStream to send data to a file // called myobject.data. FileOutputStream f_out = new FileOutputStream ("myobject.data"); // Use an ObjectOutputStream to send object data to the // FileOutputStream for writing to disk. ObjectOutputStream obj_out = new ObjectOutputStream (f_out); // Pass our object to the ObjectOutputStream's // writeObject() method to cause it to be written out // to disk. obj_out.writeObject (myObject);

And that's it. In just three lines of code, you have written "myObject" (which you can consider just any arbitrary object) out to a disk file. Note that any Java object that implements the serializable interface, including those that are part of the Java standard class library, can be written to an output stream this way.

Furthermore, any objects that are referenced by a serialized object will also be stored, provided they also are serializable. This means that arrays, vectors, lists, and collections of objects can be saved in the same fashion—without having to manually save each item individually. This can lead to significant time and code savings.

Think about it: if you have an object that contains other objects, you still can save the whole kit and caboodle to disk with no more code than the few lines above. It really can't get much easier than that!

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date