Java Reference
In-Depth Information
66
67
System.out.print(
"? "
);
68
}
69
}
70
71
// close file and terminate application
72
public static void
closeFile()
73
{
74
try
75
{
76
if
(output !=
null
)
77
output.close();
78
}
79
catch
(IOException ioException)
80
{
81
System.err.println(
"Error closing file. Terminating."
);
82
}
83
}
84
}
// end class CreateSequentialFile
Enter account number, first name, last name and balance.
Enter end-of-file indicator to end input.
?
100 Bob Blue 24.98
?
200 Steve Green -345.67
?
300 Pam White 0.00
?
400 Sam Red -42.16
?
500 Sue Yellow 224.62
?
^Z
Fig. 15.10
|
Sequential file created using
ObjectOutputStream
. (Part 3 of 3.)
Class
OutputStream
provides methods for outputting
byte
arrays and individual
byte
s, but we wish to write
objects
to a file. For this reason, lines 26-27 pass the
Input-
Stream
to class
ObjectInputStream
's constructor, which
wrap
the
OutputStream
in an
ObjectOutputStream
. The
ObjectOutputStream
object uses the
OutputStream
to write
into the file the bytes that represent entire objects. Lines 26-27 might throw an
IOExcep-
tion
if a problem occurs while opening the file (e.g., when a file is opened for writing on
a drive with insufficient space or when a read-only file is opened for writing). If so, the
program displays an error message (lines 29-33). If no exception occurs, the file is open,
and variable
output
can be used to write objects to it.
This program assumes that data is input correctly and in the proper record-number
order. Method
addRecords
(lines 37-69) performs the write operation. Lines 50-51
create an
Account
object from the data entered by the user. Line 54 calls
ObjectOutput-
Stream
method
writeObject
to write the
record
object to the output file. Only one state-
ment is required to write the
entire
object.
Method
closeFile
(lines 72-83) calls
ObjectOutputStream
method
close
on
output
to close both the
ObjectOutputStream
and
its underlying
OutputStream
. The call
to method
close
is contained in a
try
block, because
close
throws an
IOException
if the
file cannot be closed properly. When using
wrapped
streams, closing the outermost stream
also
closes the wrapped stream as well.