Java Reference
In-Depth Information
Display 10.19
Binary File I/O of Objects (part 2 of 2)
45 catch (ClassNotFoundException e)
46 {
47 System.out.println("Problems with file input.");
48 }
49 catch (IOException e)
50 {
51 System.out.println("Problems with file input.");
52 }
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.
serializable, Java assigns a serial number to each object of the class that it writes to a
stream of 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
secondary storage. Also, for some classes, it may not make sense to write objects to
secondary storage, because 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
 
 
Search WWH ::




Custom Search