Java Reference
In-Depth Information
from each other.) The situation is the same for all the other write methods that
write primitive types to binary files. However, the method
writeUTF
uses differing
numbers of bytes to store different strings in a file. Longer strings require more
bytes than shorter strings. This can present a problem to Java, because there are no
separators between data items in a binary file. The way that Java manages to make
this work is by writing some extra information at the start of each string. This extra
information tells how many bytes are used to write the string, so
readUTF
knows how
many bytes to read and convert. (The method
readUTF
will be discussed a little later
in this chapter, but, as you may have already guessed, it reads a
String
value that was
written using the UTF coding method.)
The situation with
writeUTF
is even a little more complicated than what we
discussed in the previous paragraph. Notice that we said that the information at the
start of the string code in the file tells how many
bytes
to read,
not how many characters
are in the string
. These two figures are not the same. With the UTF way of encoding,
different characters are encoded in different numbers of bytes. However, all the ASCII
characters are stored in just one byte, and you are undoubtedly using only ASCII
characters, so this difference is more theoretical than real to you now.
Reading Simple Data from a Binary File
The stream class
ObjectInputStream
is used to read from a file that has been
written to using
ObjectOutputStream
. Display 10.15 gives some of the most
commonly used methods for this class. If you compare that table with the methods for
ObjectOutputStream
given in Display 10.14, you will see that each output method
in
ObjectOutputStream
has a corresponding input method in
ObjectInputStream
.
For example, if you write an integer to a file using the method
writeInt
of
ObjectOutputStream
, then you can read that integer back with the method
readInt
of
ObjectInputStream
. If you write a number to a file using the method
writeDouble
of
ObjectOutputStream
, then you can read that number back with the method
readDouble
of
ObjectInputStream
, and so forth. Display 10.16 gives an example of
using
readInt
in this way.
Self-Test Exercises
28. How do you open the binary fi le
bindata.dat
so that it is connected to an
output stream of type
ObjectOutputStream
that is named
outputThisWay
?
29. Give two statements that will write the values of the two
double
variables
v1
and
v2
to the fi le
bindata.dat
. Use the stream
outputThisWay
that you
created as the answer to Self-Test Exercise 28.
30. Give a statement that will write the string value
"Hello"
to the fi le
bindata.dat
. Use the stream
outputThisWay
that you created as the answer
to Self-Test Exercise 28.
31. Give a statement that will close the stream
outputThisWay
created as the
answer to Self-Test Exercise 28.