Source of ArrayIODemo.java


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