//ClassObjectIODemo.java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;

public class ClassObjectIODemo
{
    public static void main(String[] args)
    {
        //Create an empty binary file
        ObjectOutputStream outputStream = null;
        String fileName = "species.records";
        try
        {
            outputStream =
                new ObjectOutputStream(new FileOutputStream(fileName));
        }
        catch(IOException e)
        {
            System.out.println("Error opening output file " + fileName + ".");
            System.exit(0);
        }

        //Write two Species objects to the binary file
        Species califCondor = new Species("California Condor", 27, 0.02);
        Species blackRhino = new Species("Black Rhino", 100, 1.0);
        try
        {
            outputStream.writeObject(califCondor);
            outputStream.writeObject(blackRhino);
            outputStream.close();
        }
        catch(IOException e)
        {
            System.out.println("Error writing to file " + fileName + ".");
            System.exit(0);
        }
        System.out.println("\nTwo species records were sent to the file "
            + fileName + ".");

        //Reopen the file, then read and display the two species objects
        //First, reopen the file
        System.out.println( "Now let's reopen the file and echo those records.");
        ObjectInputStream inputStream = null;
        try
        {
            inputStream =
                new ObjectInputStream(new FileInputStream("species.records"));
        }
        catch(IOException e)
        {
            System.out.println("Error opening the input file " + fileName + ".");
            System.exit(0);
        }


        //Read the two species objects (note the necessary casting)
        Species firstSpecies = null, secondSpecies = null;
        try
        {
            firstSpecies = (Species)inputStream.readObject();
            secondSpecies = (Species)inputStream.readObject();
            inputStream.close( );
        }
        catch(Exception e)
        {
            System.out.println("Error reading from file " +
                                fileName + ".");
            System.exit(0);
        }

        //Display the two species objects read from the file
        System.out.println("\nThe following were read from the file "
            + fileName + ":");
        System.out.println(firstSpecies);
        System.out.println();
        System.out.println(secondSpecies);
        System.out.println("\nEnd of program.");
    }
}							

