Java Reference
In-Depth Information
Display 10.19
Binary File I/O of Objects (part 3 of 3)
53
System.out.println("End of program.");
54
}
55
}
Sample Dialogue
Data sent to file.
Now let's reopen the file and display the data.
The following were read from the file:
Number = 1 Letter = A
Number = 42 Letter = Z
End of program.
type ObjectOutputStream . If the same object is written to the stream more than once,
then after the first time, Java writes only the serial number for the object and not a full
description of the object's data. This makes file I/O more efficient and makes the files
smaller. When read back out with a stream of type ObjectInputStream , duplicate
serial numbers are returned as references to the same object. Note that this means that
if two variables contain references to the same object and you write the objects to the
file and later read them from the file, then the two objects that are read will again be
references to the same object. So nothing in the structure of your object data is lost
when you write the objects to the file and later read them back.
When a serializable class has instance variables of a class type, then the classes for
the instance variables must also be serializable, and so on for all levels of class instance
variables within classes. So, a class is not serializable unless the classes for all instance
variables are also serializable.
Why aren't all classes made serializable? For security reasons. The serial number
system makes it easier for programmers to get access to the object data written to sec-
ondary storage. Also, for some classes it may not make sense to write objects to sec-
ondary storage, since they would be meaningless when read out again later. For
example, if the object contains system-dependent data, the data may be meaningless
when later read out.
class instance
variables
PITFALL: Mixing Class Types in the Same File
The best way to write and read objects using ObjectOutputStream and ObjectInput-
Stream is to store only data of one class type in any one file. If you store objects of
multiple class types or even objects of only one class type mixed in with primitive
type data, it has been our experience that the system can get confused and you could
lose data.
 
Search WWH ::




Custom Search