//ArrayIODemo.java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class ArrayIODemo
{
    public static void main(String[] args)
    {
        Species[] speciesArray1 = new Species[2];
        speciesArray1[0] = new Species("California Condor", 27, 0.02);
        speciesArray1[1] = new Species("Black Rhino", 100, 1.0);
        String fileName = "SpeciesArray.dat";
        try
        {
            ObjectOutputStream outputStream =
                new ObjectOutputStream(new FileOutputStream(fileName));
            outputStream.writeObject(speciesArray1);
            outputStream.close();
        }
        catch(IOException e)
        {
            System.out.println("Error writing to file " + fileName + ".");
            System.exit(0);
        }
        System.out.println("\nAn array of two Species objects has been "
            + "written\nto the file " + fileName + " and the file has "
            + "been closed.");
        System.out.println("Now we re-open the file for input and echo "
            + "the array contents.");
        Species[] speciesArray2 = null;
        try
        {
            ObjectInputStream inputStream = 
                new ObjectInputStream(new FileInputStream(fileName));
            speciesArray2 = (Species[])inputStream.readObject( );
            inputStream.close( );
        }
        catch(Exception e)
        {
            System.out.println("Error reading the file " + fileName + ".");
            System.exit(0);
        }
        System.out.println("\nThe following were read from "
            + "the file " + fileName + ":");
        for (int i=0; i<speciesArray2.length; i++)
        {
            System.out.println(speciesArray2[i]);
            System.out.println();
        }
        System.out.println("End of program.");
    }
}							

