Java Reference
In-Depth Information
4
public static void
main(String[] args)
throws
IOException {
5
try
(
// Create an output stream for file object.dat
6
ObjectOutputStream output =
output stream
7
new
ObjectOutputStream(
new
FileOutputStream(
"object.dat"
));
8 ) {
9
// Write a string, double value, and object to the file
10 output.writeUTF(
"John"
);
11 output.writeDouble(
85.5
);
12
output string
output.writeObject(
new
java.util.Date());
output object
13 }
14 }
15 }
An
ObjectOutputStream
is created to write data into the file
object.dat
in lines 6 and 7.
A string, a double value, and an object are written to the file in lines 10-12. To improve
performance, you may add a buffer in the stream using the following statement to replace
lines 6 and 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 17.6 reads
data from
object.dat
.
L
ISTING
17.6
TestObjectInputStream.java
1
import
java.io.*;
2
3
public class
TestObjectInputStream {
4
public static void
main(String[] args)
5
throws
ClassNotFoundException, IOException {
6
try
(
// Create an input stream for file object.dat
input stream
7
ObjectInputStream input =
8
new
ObjectInputStream(
new
FileInputStream(
"object.dat"
));
9 ) {
10
// Read a string, double value, and object from the file
11 String name = input.readUTF();
12
double
score = input.readDouble();
13 java.util.Date date = (java.util.Date)(input.readObject());
14 System.out.println(name +
" "
+ score +
" "
+ date);
15 }
16 }
17 }
input string
input object
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 and 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
Search WWH ::
Custom Search