Java Reference
In-Depth Information
10 output.writeUTF(
"John"
);
11 output.writeDouble(
85.5
);
12
13
14
// Close output stream
15 output.close();
16 }
17 }
output
output.writeObject(
new
java.util.Date());
An
ObjectOutputStream
is created to write data into the file
object.dat
in lines 6-7. A
string, a double value, and an object are written to the file in lines 10-12. To improve per-
formance, you may add a buffer in the stream using the following statement to replace
lines 6-7:
ObjectOutputStream output =
new
ObjectOutputStream(
new
BufferedOutputStream(
new
FileOutputStream(
"object.dat"
)));
Multiple objects or primitives can be written to the stream. The objects must be read back
from the corresponding
ObjectInputStream
with the same types and in the same order as
they were written. Java's safe casting should be used to get the desired type. Listing 19.6 reads
data from
object.dat
.
L
ISTING
19.6
TestObjectInputStream.java
1
import
java.io.*;
2
3
public class
TestObjectInputStream {
4
public static void
main(String[] args)
5
throws
ClassNotFoundException, IOException {
6
// Create an input stream for file object.dat
7
8
9
10
// Write a string, double value, and object to the file
11 String name = input.readUTF();
12
double
score = input.readDouble();
13 java.util.Date date = (java.util.Date)(
ObjectInputStream input =
input stream
new
ObjectInputStream(
new
FileInputStream(
"object.dat"
));
input
input.readObject()
);
14 System.out.println(name +
" "
+ score +
" "
+ date);
15
16
// Close input stream
17 input.close();
18 }
19 }
John 85.5 Sun Dec 04 10:35:31 EST 2011
The
readObject()
method may throw
java.lang.ClassNotFoundException
, because
when the JVM restores an object, it first loads the class for the object if the class has not been
loaded. Since
ClassNotFoundException
is a checked exception, the
main
method
declares to throw it in line 5. An
ObjectInputStream
is created to read input from
object.dat
in lines 7-8. You have to read the data from the file in the same order and format
as they were written to the file. A string, a double value, and an object are read in lines 11-13.
Since
readObject()
returns an
Object
, it is cast into
Date
and assigned to a
Date
variable
in line 13.
ClassNotFoundException