public class ArrayIODemo
1: //ArrayIODemo.java
2:
3: import java.io.FileInputStream;
4: import java.io.FileOutputStream;
5: import java.io.ObjectInputStream;
6: import java.io.ObjectOutputStream;
7: import java.io.IOException;
8:
9: public class ArrayIODemo
10: {
11: public static void main(String[] args)
12: {
13: Species[] speciesArray1 = new Species[2];
14: speciesArray1[0] = new Species("California Condor", 27, 0.02);
15: speciesArray1[1] = new Species("Black Rhino", 100, 1.0);
16: String fileName = "SpeciesArray.dat";
17: try
18: {
19: ObjectOutputStream outputStream =
20: new ObjectOutputStream(new FileOutputStream(fileName));
21: outputStream.writeObject(speciesArray1);
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("\nAn array of two Species objects has been "
30: + "written\nto the file " + fileName + " and the file has "
31: + "been closed.");
32: System.out.println("Now we re-open the file for input and echo "
33: + "the array contents.");
34: Species[] speciesArray2 = null;
35: try
36: {
37: ObjectInputStream inputStream =
38: new ObjectInputStream(new FileInputStream(fileName));
39: speciesArray2 = (Species[])inputStream.readObject( );
40: inputStream.close( );
41: }
42: catch(Exception e)
43: {
44: System.out.println("Error reading the file " + fileName + ".");
45: System.exit(0);
46: }
47: System.out.println("\nThe following were read from "
48: + "the file " + fileName + ":");
49: for (int i=0; i<speciesArray2.length; i++)
50: {
51: System.out.println(speciesArray2[i]);
52: System.out.println();
53: }
54: System.out.println("End of program.");
55: }
56: }
57: