Java Reference
In-Depth Information
written in the file one immediately after the other, and they are encoded as a sequence of
bytes in the same way that the numbers would be encoded in the computer's main
memory. These coded
int
values cannot be read using your editor. Realistically, they
can be read only by another Java program.
You can use a stream from the class
ObjectOutputStream
to output values of any
primitive type and also to write data of the type
String
. Each primitive data type has a
corresponding write method in the class
ObjectOutputStream
. We have already men-
tioned the write methods for outputting
int
values. The methods for the other primi-
tive types are completely analogous to
writeInt
. For example, the following would
write a
double
value, a
boolean
value, and a
char
value to the binary file connected to
the
ObjectOutputStream
object
outputStream
:
outputStream.writeDouble(9.99);
outputStream.writeBoolean(
false
);
outputStream.writeChar((
int
)'A');
The method
writeChar
has one possibly surprising property: It expects its argu-
ment to be of type
int
. So if you start with a value of type
char
, the
char
value can be
type cast to an
int
before it is given to the method
writeChar
. For example, to output
the contents of a
char
variable named
symbol
, you can use
writeChar
outputStream.writeChar((
int
)symbol);
In actual fact, you do not need to write in the type cast to an
int
, because Java auto-
matically performs a type cast from a
char
value to an
int
value for you. So, the fol-
lowing is equivalent to the above invocation of
writeChar
:
outputStream.writeChar(symbol);
To output a value of type
String
, you use the method
writeUTF
. For example, if
outputStream
is a stream of type
ObjectOutputStream
, the following will write the
string
"Hello friend."
to the file connected to that stream:
writeUTF
for strings
outputStream.writeUTF("Hello friend.");
You may write output of different types to the same file. So, you may write a com-
bination of, for example,
int
,
double
, and
String
values. However, mixing types in a
file does require special care to make it possible to read them back out of the file. To
read them back, you need to know the order in which the various types appear in the
file, because, as you will see, a program that reads from the file will use a different
method to read data of each different type.
Note that, as illustrated in Display 10.13 and as you will see shortly, you close a binary
output or input stream in the same way that you close a stream connected to a text file.
closing a
binary file
UTF and
writeUTF
Recall that Java uses the Unicode character set, a set of characters that includes many
characters used in languages whose character sets are different from English. Readers