Java Reference
In-Depth Information
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0)
(0.0,0.0) (10.0,10.0)
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0)
(0.0,0.0)
(10.0,10.0) (10.0,15.0)
File written.
Reading objects from the file:
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0)
(0.0,0.0)
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0)
(0.0,0.0)
Polyline: (1.0,1.0) (1.0,2.0) (2.0,3.0) (-3.0,5.0) (-5.0,1.0)
(0.0,0.0)
All three objects that you read from the file are equal and identical to the first object that was written.
From the output it is clear that you did modify polygon twice so there should have been three different
objects. This seems rather strange and unexpected so let's try to understand what is happening here.
How It Works
As you know, all variables of a class type store references, not objects, and in general you might have
several different variables referring to the same object in your program. For this reason, the serialization
output process keeps track of the objects that are written to the stream. Any attempt to write the same
object to the stream doesn't result in duplicates of the object being written. Only a handle , which is a sort
of reference, is written to the stream for each duplicate of an object, and this points to the first occurrence
of the object in the stream.
Consequently , the modified versions of the polygon object in the example are not written to the file. The
first write operation writes the original object referenced by polygon to the stream. For the second and
third write operations, the serialization process detects that you are writing an object that has previously
been written to the file, and so only a handle that refers back to the original unmodified version of the
object is written. The result is that the changes to the object are lost. This explains why, when you read
the three objects back from the file, they all turn out to be identical. This is not at all what you intended
in this case, so how can you avoid this?
Resetting an Object Output Stream
The appropriate course of action in such situations is obviously going to be application-dependent, but in
the previous example it is clear — you want each version of polygon explicitly written to the file. You can
make the ObjectOutputStream object forget the objects it has previously written to a stream by calling its
reset() method:
objectOut.reset(); // Reset the stream
This clears the record that is kept within the stream object of what has been written and writes a reset
marker to the stream to record that the object stream was rest at this point. Following this the output stream
object has no knowledge of what was previously written and so it will write an object that otherwise would
be ignored as a duplicate reference.
Search WWH ::




Custom Search