Download presentation
Presentation is loading. Please wait.
1
Java Serialization B.Ramamurthy 11/8/2018 B.Ramamurthy
2
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/8/2018 B.Ramamurthy
3
Topics for Discussion Object Serialization Writing to an Object Stream
Reading from an Object Stream Selective Serialization Exception Handling Example 11/8/2018 B.Ramamurthy
4
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/8/2018 B.Ramamurthy
5
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/8/2018 B.Ramamurthy
6
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/8/2018 B.Ramamurthy
7
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/8/2018 B.Ramamurthy
8
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/8/2018 B.Ramamurthy
9
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. See Lab4 for example. 11/8/2018 B.Ramamurthy
10
Example try {… } catch(Exception ex) { ex.printStackTrace();
// print the exception stack details 11/8/2018 B.Ramamurthy
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.