Java Reference
In-Depth Information
Account First Name Last Name Balance
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
No more records
Fig. 15.11
|
Reading a file of objects sequentially with
ObjectInputStream
and displaying
each record. (Part 3 of 3.)
The program reads records from the file in method
readRecords
(lines 37-66). Line
46 calls
ObjectInputStream
method
readObject
to read an
Object
from the file. To use
Account
-specific methods, we
downcast
the returned
Object
to type
Account
. Method
readObject
throws an
EOFException
(processed at lines 54-57) if an attempt is made to
read beyond the end of the file. Method
readObject
throws a
ClassNotFoundException
if the class for the object being read cannot be located. This may occur if the file is accessed
on a computer that does not have the class.
Software Engineering Observation 15.1
This section introduced object serialization and demonstrated basic serialization tech-
niques. Serialization is a deep subject with many traps and pitfalls. Before implementing
object serialization in industrial-strength applications, carefully read the online Java doc-
umentation for object serialization.
Class
JFileChooser
displays a dialog that enables the user to easily select files or directo-
ries. To demonstrate
JFileChooser
, we enhance the example in Section 15.3, as shown in
Figs. 15.12-15.13. The example now contains a graphical user interface, but still displays
the same data as before. The constructor calls method
analyzePath
in line 24. This meth-
od then calls method
getFileOrDirectoryPath
in line 31 to retrieve a
Path
object repre-
senting the selected file or directory.
Method
getFileOrDirectoryPath
(lines 71-85 of Fig. 15.12) creates a
JFile-
Chooser
(line 74). Lines 75-76 call method
setFileSelectionMode
to specify what the
user can select from the
fileChooser
. For this program, we use
JFileChooser
static
constant
FILES_AND_DIRECTORIES
to indicate that files and directories can be selected.
Other
static
constants include
FILES_ONLY
(the default) and
DIRECTORIES_ONLY
.
Line 77 calls method
showOpenDialog
to display the
JFileChooser
dialog titled
Open
.
Argument
this
specifies the
JFileChooser
dialog's parent window, which determines the
position of the dialog on the screen. If
null
is passed, the dialog is displayed in the center
of the screen—otherwise, the dialog is centered over the application window (specified by
the argument
this
). A
JFileChooser
dialog is a
modal dialog
that does not allow the user
to interact with any other window in the program until the dialog is closed. The user selects
the drive, directory or filename, then clicks
Open
. Method
showOpenDialog
returns an
integer specifying which button (
Open
or
Cancel
) the user clicked to close the dialog. Line