Java Reference
In-Depth Information
Display 10.13
Writing to a Binary File
(part 2 of 2)
18
catch
(IOException e)
19 {
20 System.out.println("Problem with file output.");
21 }
22 }
23 }
F
ILE
R
EPRESENTATION
(after program is run)
0
1
2
3
4
This is a binary file. It really contains representations
of each number as bytes—that is, zeros and ones—and
is read as bytes. You cannot read this file with your
text editor.
Display 10.14
Some Methods in the Class
ObjectOutputStream
(part 1 of 2)
ObjectOutputStream
and
FileOutputStream
are in the
java.io package.
public
ObjectOutputStream(OutputStream streamObject)
There is no constructor that takes a file name as an argument. If you want to create a stream using
a file name, use
new
ObjectOutputStream(
new
FileOutputStream(
File_Name
))
This creates a blank file. If there already is a file named
File_Name
, then the old contents of the
file are lost.
If you want to create a stream using an object of the class
File
, use
new
ObjectOutputStream(
new
FileOutputStream(
File_Object
))
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
.
public void
writeInt(
int
n)
throws
IOException
Writes the
int
value
n
to the output stream.
public void
writeShort(
short
n)
throws
IOException
Writes the
short
value
n
to the output stream.
public void
writeLong(
long
n)
throws
IOException
Writes the
long
value
n
to the output stream.
public void
writeDouble(
double
x)
throws
IOException
Writes the
double
value
x
to the output stream.
(continued)