Source of BinaryInputDemo.java


  1: //BinaryInputDemo.java

  3: import java.io.FileInputStream;
  4: import java.io.ObjectInputStream;
  5: import java.io.FileNotFoundException;
  6: import java.io.EOFException;
  7: import java.io.IOException;
  8: import java.util.Scanner;

 10: public class BinaryInputDemo
 11: {
 12:   public static void main(String[] args)
 13:   {
 14:      String fileName = "numbers.dat";
 15:      try
 16:      {
 17:          ObjectInputStream inputStream = 
 18:              new ObjectInputStream(new FileInputStream(fileName));
 19:          System.out.println("\nReading all nonnegative integers"
 20:              + "from the file " + fileName + ",\nup to "
 21:              + "first negative sentinel value:");
 22:          int anInteger = inputStream.readInt();
 23:          while (anInteger >= 0)
 24:          {
 25:              System.out.println(anInteger);
 26:              anInteger = inputStream.readInt();
 27:          }
 28:          System.out.println("Finished reading from the file.");
 29:          inputStream.close();
 30:      }
 31:      catch(FileNotFoundException e)
 32:      {
 33:          System.out.println("Error opening the file " + fileName + ".");
 34:      }
 35:      catch(EOFException e)
 36:      {
 37:          System.out.println("Error reading the file " + fileName + ".");
 38:          System.out.println("Encountered the end of the file.");
 39:      }
 40:      catch(IOException e)
 41:      {
 42:          System.out.println("Error reading input from file " + fileName + ".");
 43:      }
 44:   }
 45: }