Java Reference
In-Depth Information
numbers[0] = 0.2639251629586685
numbers[1] = 0.7212385629586818
numbers[2] = 0.9652574768726307
numbers[3] = 0.4347419118504684
numbers[4] = 0.38425335784130443
A little knowledge is a dangerous thing.
42
numbers[0] = 0.20540865153372645
numbers[1] = 0.14819027494615766
numbers[2] = 0.966333475583602
Flies light on lean horses.
42
numbers[0] = 0.582505845190295
numbers[1] = 0.7568767131705605
numbers[2] = 0.031276131457401934
numbers[3] = 0.22867560732800996
numbers[4] = 0.030591566057953434
EOF reached. 3 objects read.
You should get output corresponding to the objects that were written to your file.
How It Works
You first define the Path object that encapsulates the path to the file containing the objects to be read
and verify that it does indeed exist. You use the objectCount variable to accumulate a count of the total
number of objects read from the stream.
To make the program a little more general, the read operation is in a loop to show how you might read
the file when you don't know how many objects there are in it. The object variable stores the reference
to each object that you read. To read each object, you just call the readObject() method for the input
stream and cast the reference that is returned to type Junk before storing it in object .
So you can see what you have read from the file, the string representation of each object is displayed on
the command line. The while loop continues to read objects from the stream indefinitely. When the end
of the file is reached, an exception of type EOFException is thrown. This effectively terminates the loop,
and the code in the catch block for this exception executes. This outputs a message to the command line
showing the number of objects that were read. In spite of the try block being terminated by an exception
being thrown, the stream is still closed automatically. The catch block for EOFException must precede
the block that catches IOException because EOFException is a subclass of IOException .
As you can see, you get back all the objects that you wrote to the file originally. This is obviously very
encouraging — getting fewer objects than you wrote would be inconvenient to say the least, and getting
more would be worrying.
Determining the Class of a Deserialized Object
The readObject() method returns the object that it reads from the stream as type Object so you need to
know what the original type of the object was to be able to cast it to its actual type. For the most part, you
will know what the class of the object is when you read it back. It is possible that in some circumstances you
won't know exactly, but you will have a rough idea, in which case you can test it. To bring the problem into
sharper focus, consider a hypothetical situation.
Search WWH ::




Custom Search