//BinaryOutputDemo.java

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class BinaryOutputDemo
{
    public static void main(String[] args)
    {
        String fileName = "numbers.dat";
        try
        {
            ObjectOutputStream outputStream =
                new ObjectOutputStream(new FileOutputStream(fileName));
            Scanner keyboard = new Scanner(System.in);
            System.out.println("\nEnter some nonnegative integers, "
                + "followed\nby a single negative integer at the end:");
            int anInteger;
            do
            {
                anInteger = keyboard.nextInt();
                outputStream.writeInt(anInteger);
            }
            while (anInteger >= 0);
            System.out.println("All integers, plus the sentinel value, "
                + "\nhave been written to the file " + fileName + ".");
            outputStream.close();
        }
        catch(FileNotFoundException e)
        {
            System.out.println("Error opening the file " + fileName + ".");
        }
        catch(IOException e)
        {
            System.out.println("Problem with output to file " + fileName + ".");
        }
    }
}

