Java Reference
In-Depth Information
14. 2025551212L, bday1, “Toontown”);
15. Contact2 two = new Contact2(“Daffy Duck”, 33,
16. 3035551212L, bday2, “Toontown”);
17.
18. File contactsFile = new File(“mycontacts.ser”);
19. FileOutputStream fos =
20. new FileOutputStream(contactsFile);
21. ObjectOutputStream out = new ObjectOutputStream(fos);
22.
23. out.writeObject(one);
24. out.writeObject(two);
25.
26. out.close();
27. fos.close();
28. }catch(IOException e) {
29. e.printStackTrace();
30. }
31. }
32. }
There is no output, but the SerializeDemo program does create a new fi le named my
contacts.ser that contains two serialized objects of type Contact2 . The lines of code
to focus on in this program are lines 23 and 24. Calling writeObject and passing in a
Contact2 reference serializes the object and writes it to the mycontacts.ser fi le.
Now that we have seen how to serialize objects, let's look at the code to deserialize them
using the ObjectInputStream class.
The ObjectInputStream Class
An ObjectInputStream deserializes objects from an input stream. It is a high-level stream
that needs to be chained to a low-level stream that represents the source of the serialized
objects. You should know how to use FileInputStream with ObjectInputStream , and I
discuss an example of using these two classes as we deserialize the two Contact2 objects
from the SerializeDemo program in the previous section.
The ObjectInputStream class contains read methods that correspond to the write meth-
ods of ObjectOutputStream , including public Object readObject() throws IOExcep-
tion, ClassNotFoundException .
The readObject method deserializes the next object in the stream. Note the reference
type of the return value is Object . Typically we need to cast the reference to its appropriate
class type.
The following DeserializeDemo program deserializes two objects from the mycontacts.
ser fi le created in SerializeDemo . Assuming the SerializeDemo program is executed once,
see if you can determine the output of this program:
Search WWH ::




Custom Search