Java Reference
In-Depth Information
Transient Data Members of a Class
If your class has fields that are not serializable, or that you just don't want to have written to the stream,
you can declare them as transient . For example:
public class MyClass implements Serializable {
transient protected Graphics g; // Transient class member
// Rest of the class definition
}
Declaring a data member as transient will prevent the writeObject() method from attempting to
write the data member to the stream. When the class object is read back, it will be created properly,
including any members that you declared as transient . They just won't have their values set, because
they were not written to the stream. Unless you arrange for something to be done about it, the transient
fields will be null.
You may well want to declare some data members of a class as transient . You would do this when
they have a value that is not meaningful long term or out of context - objects that represent the current
time, or today's date, for instance. You must either provide code to explicitly reconstruct the members
that you declare as transient when the object that contains them is read from the stream or accept
the construction time defaults.
Reading an Object from a File
Reading objects back from a file is just as easy as writing them. First, you need to create an
ObjectInputStream object for the file. To do this you just pass a reference to a FileInputStream
object that encapsulates the file to the ObjectInputStream class constructor:
File theFile = new File("MyFile");
// Perhaps check out the file...
// Create the object output stream for the file
ObjectInputStream objectIn = null;
try {
objectIn = new ObjectInputStream(new FileInputStream(theFile));
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
The ObjectInputStream constructor will throw an exception of type
StreamCorruptedException - a subclass of IOException - if the stream header is not correct, or
of type IOException if an error occurs while reading the stream header. Of course, as we saw in the
last chapter, the FileInputStream constructor can throw an exception of type
FileNotFoundException .
Once you have created the ObjectInputStream object you call its readObject() method to read
an object from the file:
Search WWH ::




Custom Search