Java Reference
In-Depth Information
Notice that almost all the code in the sample program in Display 10.13 is in a
try
block. Any part of the code that does binary file I/O in the ways we are describing can
throw an
IOException
.
The output stream for writing to the binary file
numbers.dat
is created and named
with the following:
ObjectOutputStream outputStream =
new
ObjectOutputStream(
new
FileOutputStream("numbers.dat"));
As with text files, this is called
opening the file
. If the file
numbers.dat
does not
already exist, this statement will create an empty file named
numbers.dat
. If the file
numbers.dat
already exists, this statement will erase the contents of the file so that the
file starts out empty. The situation is basically the same as what you learned for text
files, except that we're using a different class.
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 file
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 con-
structor 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
writeInt