Java Reference
In-Depth Information
Display 10.20
File I/O of an Array Object
(part 2 of 3)
21
catch
(IOException e)
22
{
23
System.out.println("Error writing to file.");
24
System.exit(0);
25
}
26
System.out.println(
27
"Array written to file arrayfile.");
28
System.out.println(
29
"Now let's reopen the file and display the array.");
30
SomeClass[] b =
null
;
31
try
32
{
33
ObjectInputStream inputStream =
34
new
ObjectInputStream(
new
FileInputStream("arrayfile"));
35
b = (SomeClass[])inputStream.readObject();
36
inputStream.close();
37
}
Notice the type cast.
38
catch
(FileNotFoundException e)
39
{
40
System.out.println("Cannot find file arrayfile.");
41
System.exit(0);
42
}
43
catch
(ClassNotFoundException e)
44
{
45
System.out.println("Problems with file input.");
46
System.exit(0);
47
}
48
catch
(IOException e)
49
{
50
System.out.println("Problems with file input.");
51
System.exit(0);
52
}
53
System.out.println(
54
"The following array elements were read from the file:");
55
int
i;
56
for
(i = 0; i < b.length; i++)
57
System.out.println(b[i]);
58
System.out.println("End of program.");
59
}
60
}
(continued)