Java Reference
In-Depth Information
1. package com.sybex.io;
2.
3. import java.io.*;
4. import java.util.GregorianCalendar;
5.
6. public class DeserializeDemo {
7. public static void main(String [] args) {
8. try {
9. File contactsFile = new File(“mycontacts.ser”);
10. FileInputStream fis =
11. new FileInputStream(contactsFile);
12. ObjectInputStream in = new ObjectInputStream(fis);
13.
14. while(fis.available() > 0) {
15. Object obj = in.readObject();
16. if(obj instanceof Contact2) {
17. Contact2 contact = (Contact2) obj;
18. System.out.println(contact);
19. System.out.println(“city = “
20. + contact.getCity());
21. }
22. }
23.
24. in.close();
25. fis.close();
26. }catch(IOException e) {
27. e.printStackTrace();
28. }catch(ClassNotFoundException c) {
29. c.printStackTrace();
30. }
31. }
32. }
The
while
loop on line 14 reads in objects from the
mycontacts.ser
fi le until the stream
is empty. Two objects are in the fi le, so the
while
loop executes twice. The
instanceof
comparison on line 16 is
true
for both objects and line 18 prints the
Contact2
object,
outputting the result of its
toString
method. I added line 19 to explicitly illustrate that
the
city
fi eld did not get serialized because it was declared
transient
. Transient fi elds are
ignored during serialization and initialized to their “zero” value during deserialization,
which for references is
null
. The output of the
DeserializeDemo
program is
Search WWH ::
Custom Search