Java Reference
In-Depth Information
}
// Close the stream
try {
objectIn.close(); // Close the input stream
} catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
}
I got the output:
A green twig is easily bent.
42
numbers[0] = 0.20157825618636616
numbers[1] = 0.7123542196242817
numbers[2] = 0.8027761971323069
A little knowledge is a dangerous thing.
42
numbers[0] = 0.929629487353265
numbers[1] = 0.5402881072148746
numbers[2] = 0.03259660544653753
numbers[3] = 0.94945294401263
numbers[4] = 0.17383591141346522
Flies light on lean horses.
42
numbers[0] = 0.6765377168813207
numbers[1] = 0.3933764846876555
numbers[2] = 0.7633265658906377
numbers[3] = 0.31411955819992887
EOF reached. 3 objects read.
You should get output corresponding to the objects that were written to your file.
How It Works
We first define the objectIn variable that will store the reference to the stream. We will use the
objectCount variable to accumulate a count of the total number of objects read from the stream. The
object variable will store the reference to each object that we read. To make the program a little more
general, we have implemented the read operation in a loop to show how you might read the file when
you don't know how many objects there are in it. To read each object, we just call the readObject()
method for the input stream and cast the reference returned to type Junk before storing it in object .
So we can see what we have read, the string representation of each object is displayed on the command
line. The while loop will continue indefinitely reading objects from the stream. When the end of the
file is reached, an exception of type EOFExcepion will be thrown so the loop will be terminated and
the code in the catch block for this exception will execute. This outputs a message to the command
line showing the number of objects that were read. As you can see, we get back all the objects that we
wrote to the file originally.
Search WWH ::




Custom Search