Java Reference
In-Depth Information
31
System.err.println(
"Error opening file."
);
32
System.exit(
1
);
33
}
34
}
35
36
// read record from file
37
public static void
readRecords()
38
{
39
System.out.printf(
"%-10s%-12s%-12s%10s%n"
,
"Account"
,
40
"First Name"
,
"Last Name"
,
"Balance"
);
41
42
try
43
{
44
while
(
true
)
// loop until there is an EOFException
45
{
46
Account record = (Account) input.readObject();
47
48
// display record contents
49
System.out.printf(
"%-10d%-12s%-12s%10.2f%n"
,
50
record.getAccount(), record.getFirstName(),
51
record.getLastName(), record.getBalance());
52
}
53
}
54
catch
(EOFException endOfFileException)
55
{
56
System.out.printf(
"%No more records%n"
);
57
}
58
catch
(ClassNotFoundException classNotFoundException)
59
{
60
System.err.println(
"Invalid object type. Terminating."
);
61
}
62
catch
(IOException ioException)
63
{
64
System.err.println(
"Error reading from file. Terminating."
);
65
}
66
}
// end method readRecords
67
68
// close file and terminate application
69
public static void
closeFile()
70
{
71
try
72
{
73
if
(input !=
null
)
74
input.close();
75
}
76
catch
(IOException ioException)
77
{
78
System.err.println(
"Error closing file. Terminating."
);
79
System.exit(
1
);
80
}
81
}
82
}
// end class ReadSequentialFile
Fig. 15.11
|
Reading a file of objects sequentially with
ObjectInputStream
and displaying
each record. (Part 2 of 3.)