Source of ArrayIODemo.java


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