public class ArrayIODemo
1: //ArrayIODemo.java
2:
3: import java.io.FileInputStream;
4: import java.io.FileOutputStream;
5: import java.io.IOException;
6: import java.io.ObjectInputStream;
7: import java.io.ObjectOutputStream;
8:
9: public class ArrayIODemo
10: {
11: public static void main(String[] args)
12: {
13: Species[] oneArray = new Species[2];
14: oneArray[0] = new Species("Calif. Condor", 27, 0.02);
15: oneArray[1] = new Species("Black Rhino", 100, 1.0);
16: String fileName = "array.dat";
17: try
18: {
19: ObjectOutputStream outputStream =
20: new ObjectOutputStream(new FileOutputStream(fileName));
21: outputStream.writeObject(oneArray);
22: outputStream.close();
23: }
24: catch (IOException e)
25: {
26: System.out.println("Error writing to file " + fileName + ".");
27: System.exit(0);
28: }
29: System.out.println("Array written to file " + fileName
30: + " and file is closed.");
31: System.out.println("Open the file for input and echo the array.");
32: Species[] anotherArray = null;
33: try
34: {
35: ObjectInputStream inputStream =
36: new ObjectInputStream(new FileInputStream(fileName));
37: anotherArray = (Species[])inputStream.readObject();
38: inputStream.close();
39: }
40: catch (Exception e)
41: {
42: System.out.println("Error reading file " + fileName + ".");
43: System.exit(0);
44: }
45: System.out.println("The following were read from " + "the file "
46: + fileName + ":");
47: for (int i = 0; i < anotherArray.length; i++)
48: {
49: System.out.println(anotherArray[i]);
50: System.out.println();
51: }
52: System.out.println("End of program.");
53: }
54: }