Java Reference
In-Depth Information
As is typical of Java I/O classes, the constructor for the class
ObjectOutputStream
takes another I/O class object as an argument—in this case, an anonymous argument
of the class
FileOutputStream
.
Opening a Binary File for Output
You create a stream of the class
ObjectOutputStream
and connect it to a binary file
as follows:
SYNTAX
ObjectOutputStream
Output_Stream_Name
=
new
ObjectOutputStream(
new
FileOutputStream(
File_Name
));
The constructor for
FileOutputStream
may throw a
FileNotFoundException
, which
is a kind of
IOException
. If the
FileOutputStream
constructor succeeds, then the
constructor for
ObjectOutputStream
may throw a different
IOException
. A single
catch
block for
IOException
would cover all cases.
EXAMPLES
ObjectOutputStream myOutputStream =
new
ObjectOutputStream(
new
FileOutputStream("mydata.dat"));
After opening the file, you can use the methods of the class
ObjectOutputStream
(Display 10.14) to write to the file.
The class
ObjectOutputStream
does not have a method named
println
, as we had
with text file output and screen output. However, as shown in Display 10.13, an object of
the class
ObjectOutputStream
does have a method named
writeInt
that can write a single
int
value to a file, and it also has the other output methods described in Display 10.14.
In Display 10.13, we made it look as though the numbers in the file
numbers.dat
were written one per line in a human-readable form. That is not what happens,
however. There are no lines or other separators between the numbers. Instead, the
numbers are 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
mentioned the write methods for outputting
int
values. The methods for the other
primitive 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
:
writeInt
outputStream.writeDouble(9.99);
outputStream.writeBoolean(
false
);
outputStream.writeChar((
int
)'A');