Source of Question21.java


  1: //Question21.java
  2: 
  3: import java.io.EOFException;
  4: import java.io.FileInputStream;
  5: import java.io.FileNotFoundException;
  6: import java.io.ObjectInputStream;
  7: import java.io.IOException;
  8: import java.util.Scanner;
  9: 
 10: public class Question21
 11: {
 12:     public static void main(String[] args)
 13:     {
 14:         //To use fileName in a catch block, 
 15:         //declare it outside of the try block
 16:         String fileName = null;
 17:         try
 18:         {
 19:             System.out.println("Enter file name:");
 20:             Scanner keyboard = new Scanner(System.in);
 21:             fileName = keyboard.next();
 22:             ObjectInputStream inputStream =
 23:                 new ObjectInputStream(new FileInputStream(fileName));
 24:             System.out.println("The first thing in the file");
 25:             System.out.println(fileName + " is");
 26:             String first = inputStream.readUTF();
 27:             System.out.println(first);
 28:             inputStream.close();
 29:         }
 30:         catch (FileNotFoundException e)
 31:         {
 32:             System.out.println("Problem opening the file " + fileName);
 33:         }
 34:         catch (EOFException e)
 35:         {
 36:             System.out.println("Unexpected end of file.");
 37:         }
 38:         catch (IOException e)
 39:         {
 40:             System.out.println("Problem with input from file " + fileName);
 41:         }
 42:     }
 43: }