Java Reference
In-Depth Information
Display 10.20
File I/O of an Array Object (part 2 of 3)
10 {
11 SomeClass[] a = new SomeClass[2];
12 a[0] = new SomeClass(1, 'A');
13 a[1] = new SomeClass(2, 'B');
14 try
15 {
16 ObjectOutputStream outputStream =
17 new ObjectOutputStream( new FileOutputStream("arrayfile"));
18 outputStream.writeObject(a);
19 outputStream.close( );
20 }
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 }
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
Notice the type cast.
int i;
(continued)
Search WWH ::




Custom Search