Source of BinaryOutputDemo.java


  1: //BinaryOutputDemo.java
  2: 
  3: import java.io.FileOutputStream;
  4: import java.io.ObjectOutputStream;
  5: import java.io.FileNotFoundException;
  6: import java.io.File;
  7: import java.io.IOException;
  8: import java.util.Scanner;
  9: 
 10: public class BinaryOutputDemo
 11: {
 12:     public static void main(String[] args)
 13:     {
 14:         String fileName = "numbers.dat";
 15:         try
 16:         {
 17:             ObjectOutputStream outputStream =
 18:                 new ObjectOutputStream(new FileOutputStream(fileName));
 19:             Scanner keyboard = new Scanner(System.in);
 20:             System.out.println("Enter nonnegative integers.");
 21:             System.out.println("Place a negative number at the end.");
 22: 
 23:             int anInteger;
 24:             do
 25:             {
 26:                 anInteger = keyboard.nextInt();
 27:                 outputStream.writeInt(anInteger);
 28:             }
 29:             while (anInteger >= 0);
 30:             System.out.println("Numbers and sentinel value");
 31:             System.out.println("written to the file " + fileName);
 32:             outputStream.close();
 33:         }
 34:         catch (FileNotFoundException e)
 35:         {
 36:             System.out.println("Problem opening the file " + fileName);
 37:         }
 38:         catch (IOException e)
 39:         {
 40:             System.out.println("Problem with output to file " + fileName);
 41:         }
 42:     }
 43: }