Java Reference
In-Depth Information
LISTING 16.2
The Full Text of ObjectReader.java
1: import java.io.*;
2: import java.util.*;
3:
4: public class ObjectReader {
5: public static void main(String[] arguments) {
6: try {
7: FileInputStream fi = new FileInputStream(
8: “message.obj”);
9: ObjectInputStream oi = new ObjectInputStream(fi);
10: Message mess = (Message) oi.readObject();
11: System.out.println(“Message:\n”);
12: System.out.println(“From: “ + mess.from);
13: System.out.println(“To: “ + mess.to);
14: System.out.println(“Date: “ + mess.when + “\n”);
15: for (int i = 0; i < mess.lineCount; i++)
16: System.out.println(mess.text[i]);
17: oi.close();
18: } catch (Exception e) {
19: System.out.println(“Error — “ + e.toString());
20: }
21: }
22: }
16
The output of this program is as follows:
Message:
From: Sam Wainwright, London
To: George Bailey, Bedford Falls
Date: Sat Jan 13 20:53:40 EST 2007
Mr. Gower cabled you need cash. Stop.
My office instructed to advance you up to twenty-five
thousand dollars. Stop. Hee-haw and Merry Christmas.
Transient Variables
When creating an object that can be serialized, one design consideration is whether all
the object's instance variables should be saved.
In some cases, an instance variable must be created from scratch each time the object is
restored. A good example is an object referring to a file or input stream. Such an object
must be created anew when it is part of a serialized object loaded from an object stream,
so it doesn't make sense to save this information when serializing the object.
 
Search WWH ::




Custom Search