Java Reference
In-Depth Information
Display 10.14
Some Methods in the Class
ObjectOutputStream
(part 2 of 2)
public void
writeFloat(
float
x)
throws
IOException
Writes the
float
value
x
to the output stream.
public void
writeChar(
int
n)
throws
IOException
Writes the
char
value
n
to the output stream. Note that it expects its argument to be an
int
value. However, if you simply use the
char
value, then Java will automatically type cast it to an
int
value. The following are equivalent:
outputStream.writeChar((
int
)'A');
and
outputStream.writeChar('A');
public void
writeUTF(String aString)
throws
IOException
Writes the
String
value
aString
to the output stream.
UTF
refers to a particular method of
encoding the string. To read the string back from the file, you should use the method
readUTF
of
the class
ObjectInputStream
.
public void
writeObject(Object anObject)
throws
IOException
Writes its argument to the output stream. The object argument should be an object of a serializable
class, a concept discussed later in the section titled “The
Serializable
Interface.” Throws
various
IOExceptions
.
public void
close()
throws
IOException
Closes the stream's connection to a file. This method calls
flush
before closing the file.
public void
flush()
throws
IOException
Flushes the output stream. This forces an actual physical write to the file of any data that has been
buffered and not yet physically written to the file. Normally, you should not need to invoke
flush
.
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 are using a different class.
opening a file