Java Serialization B.Ramamurthy 11/14/2018 B.Ramamurthy
Introduction The capability to store and retrieve Java objects is essential to building persistence and streaming into application. In this lecture we will discuss details about Serialization and saving and restoring objects in files. 11/14/2018 B.Ramamurthy
Topics for Discussion Object Serialization Writing to an Object Stream Reading from an Object Stream Selective Serialization Exception Handling Example 11/14/2018 B.Ramamurthy
Persistence The values of the data structures in a program are lost when the program terminates. If you want the data to exist after program termination you need to store it in a file or in a database. We will look at file input/output in this discussion. 11/14/2018 B.Ramamurthy
Object Serialization Key to storing and retrieving objects is representing the “state” of the objects in a serialized form sufficient to reconstruct the objects. Object <===>byte stream, other data to help in reconstruction Converting an object into an organized byte form for storage, streaming etc. 11/14/2018 B.Ramamurthy
How to use Serialization? 1. import java.io.*; 2. Implement java.io.Serialization interface. 3. Use writeObject and readObject methods whose header are as given below: void writeObject (Object obj) throws IOException; Object readObject() thorws ClassNotFoundException, IOException; 11/14/2018 B.Ramamurthy
Writing to an Object Stream // serilaize various objects into a file FileOutputStream f = new FileOutputStream(“tmp”); ObjectOutputStream s = new ObjectOutputStream(f); s.writeObject(“Today”); s.writeObject(new Date()); Theater t = new Theater(4,6,10); //4 shows, 6 rows, 10 cols s.writeObject(t); 11/14/2018 B.Ramamurthy
Reading from an Object Stream // Deserialize a objects from a file FileInputStream inf = new FileInputStream(“tmp”); ObjectInputStream s1 = new ObjectInputStream(inf); //read the Object and cast to retrieve the // actual object String = (String)s1.readObject(); Data date = (Date)s1.readObject(); 11/14/2018 B.Ramamurthy
Serialization URL http://java.sun.com/products//jdk/1.1/docs/guide/serialization/index.html 11/14/2018 B.Ramamurthy
Exception Handling When ever you deal with IO you need make sure the file creation was successful accessing the files. So enclose creation of file object and stream object within try and catch. 11/14/2018 B.Ramamurthy
Example try {… } catch(Exception ex) { ex.printStackTrace(); // print the exception stack details 11/14/2018 B.Ramamurthy
Exception URL http://java.sun.com/docs/books/tutorial/essential/exceptions/QandE/answers.html 11/14/2018 B.Ramamurthy