Java Reference
In-Depth Information
14
public static void
main(String[] args)
15
{
16
openFile();
17
addRecords();
18
closeFile();
19
}
20
21
// open file clients.ser
22
public static void
openFile()
23
{
24
try
25
{
26
output =
new
ObjectOutputStream(
Files.newOutputStream(Paths.get(
"clients.ser"
)));
27
28
}
29
catch
(IOException ioException)
30
{
31
System.err.println(
"Error opening file. Terminating."
);
32
System.exit(
1
);
// terminate the program
33
}
34
}
35
36
// add records to file
37
public static void
addRecords()
38
{
39
Scanner input =
new
Scanner(System.in);
40
41
System.out.printf(
"%s%n%s%n? "
,
42
"Enter account number, first name, last name and balance."
,
43
"Enter end-of-file indicator to end input."
);
44
45
while
(input.hasNext())
// loop until end-of-file indicator
46
{
47
try
48
{
49
// create new record; this example assumes valid input
50
Account record =
new
Account(input.nextInt(),
51
input.next(), input.next(), input.nextDouble());
52
53
// serialize record object into file
output.writeObject(record);
54
55
}
56
catch
(NoSuchElementException elementException)
57
{
58
System.err.println(
"Invalid input. Please try again."
);
59
input.nextLine();
// discard input so user can try again
60
}
61
catch
(IOException ioException)
62
{
63
System.err.println(
"Error writing to file. Terminating."
);
64
break
;
65
}
Fig. 15.10
|
Sequential file created using
ObjectOutputStream
. (Part 2 of 3.)