Java Reference
In-Depth Information
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
}
This is a simple program that writes three objects to the file and records on the command line what
objects were written. It then reads the objects back from the file and writes details of the objects that
were read to the command line. When you run it you should see the output:
1st Object written has value: 1
2nd Object written has value: 2
3rd Object written has value: 3
Reading objects from the file:
1st object is Equal to 2nd object.
2nd object is Equal to 3rd object.
data1 = 1 data2 = 1 data3 = 1
All three objects that we read from the file are equal and identical to the first object that was written.
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 you may 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 will not
result in duplicates of the object being written. Only a handle , which is a sort of reference, will be written to
the stream and this will point to the first occurrence of the object in the stream.
Thus, in our example, the modified versions of the Data object will not be written to the file. The first write
operation writes the original object referenced by Data to the stream. For the second and third write
operations, the serialization process detects that we are writing an object that has previously been written to
the file, and so only a handle that refers to the original unmodified version of the object will be written, and
so the changes will be lost. This explains why, when we read the three objects back from the file, they all turn
out to be identical. This is not what we intended in this case, so how can we get over this?
Resetting an Object Output Stream
The appropriate course of action in such situations is obviously going to be application dependent but
in our example it is clear - we want each version of Data 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
Search WWH ::




Custom Search