Java Reference
In-Depth Information
Self-Test Exercises
28. How do you open the binary file
bindata.dat
so that it is connected to an out-
put stream of type
ObjectOutputStream
that is named
outputThisWay
?
29. Give two statements that will write the values of the two
double
variables
v1
and
v2
to the file
bindata.dat
. Use the stream
outputThisWay
that you created as
the answer to Self-Test Exercise 28.
30. Give a statement that will write the string value
"Hello"
to the file
bindata.dat
.
Use the stream
outputThisWay
that you created as the answer to Self-Test
Exercise 28.
31. Give a statement that will close the stream
outputThisWay
created as the answer
to Self-Test Exercise 28.
then you can read that number back with the method
readDouble
of
ObjectInput-
Stream
, and so forth. Display 10.16 gives an example of using
readInt
in this way.
Display 10.15
Some Methods in the Class
ObjectInputStream
(part 1 of 3)
The classes
ObjectInputStream
and
FileInputStream
are in the
java.io
package.
public
ObjectInputStream(InputStream streamObject)
There is no constructor that takes a file name as an argument. If you want to create a stream using a
file name, you use
new
ObjectInputStream(
new
FileInputStream(
File_Name
))
Alternatively, you can use an object of the class
File
in place of the
File_Name
, as follows:
new
ObjectInputStream(
new
FileInputStream(
File_Object
))
The constructor for
FileInputStream
may throw a
FileNotFoundException
, which is a kind of
IOException
. If the
FileInputStream
constructor succeeds, then the constructor for
ObjectIn-
putStream
may throw a different
IOException
.
public int
readInt()
throws
IOException
Reads an
int
value from the input stream and returns that
int
value. If
readInt
tries to read a value
from the file and that value was not written using the method
writeInt
of the class
ObjectOutput-
Stream
(or written in some equivalent way), then problems will occur. If an attempt is made to read
beyond the end of the file, an
EOFException
is thrown.
public int
readShort()
throws
IOException
Reads a
short
value from the input stream and returns that
short
value. If
readShort
tries to read
a value from the file and that value was not written using the method
writeShort
of the class
ObjectOutputStream
(or written in some equivalent way), then problems will occur. If an attempt is
made to read beyond the end of the file, an
EOFException
is thrown.
(continued)