
import java.io.*;

public class ClassIODemo
{
    public static void main(String[] args)
    {
        ObjectOutputStream outputStream = null;

        try
        {
            outputStream =
                  new ObjectOutputStream(
                      new FileOutputStream("species.records"));
        }
        catch(IOException e)
        {
            System.out.println(
                     "Error opening file species.records.");
            System.out.println("for writing.");
            System.exit(0);
        }

        Species oneRecord =
                    new Species("Calif. Condor", 27, 0.02);
        Species secondRecord =
                    new Species("Black Rhino", 100, 1.0);
        try
        {
            outputStream.writeObject(oneRecord);
            outputStream.writeObject(secondRecord);
            outputStream.close( );
        }
        catch(IOException e)
        {
            System.out.println(
                     "Error writing to file species.records.");
            System.exit(0);
        }

        System.out.println(
                   "Records sent to file species.record.");
        System.out.println(
              "Now let's reopen the file and echo the records.");
        ObjectInputStream inputStream = null;

        try
        {
            inputStream =
                 new ObjectInputStream(
                      new FileInputStream("species.records"));
        }
        catch(IOException e)
        {
            System.out.println(
                     "Error opening file species.records.");
            System.out.println("for reading.");
            System.exit(0);
        }

        Species readOne = null, readTwo = null;

        try
        {
            readOne = (Species)inputStream.readObject( );
            readTwo = (Species)inputStream.readObject( );
            inputStream.close( );
       }
        catch(Exception e)
        {
            System.out.println(
                     "Error reading from file species.records.");
            System.exit(0);
        }
        System.out.println("The following were read\n"
                         + "from the file species.record:");
        System.out.println(readOne);
        System.out.println( );
        System.out.println(readTwo);
        System.out.println("End of program.");
    }
}
