Source of TextFileInputDemo2.java


  1: //TextFileInputDemo2.java
  2: 
  3: import java.util.Scanner;
  4: import java.io.File;
  5: import java.io.FileNotFoundException;
  6: 
  7: public class TextFileInputDemo2
  8: {
  9:     public static void main(String[] args)
 10:     {
 11:         System.out.print("Enter file name: ");
 12:         Scanner keyboard = new Scanner(System.in);
 13:         String fileName = keyboard.next();
 14: 
 15:         Scanner inputStream = null;
 16:         System.out.println("The file " + fileName
 17:             + "\ncontains the following lines:\n");
 18: 
 19:         try
 20:         {
 21:             inputStream = new Scanner(new File(fileName));
 22:         }
 23:         catch (FileNotFoundException e)
 24:         {
 25:             System.out.println("Error opening the file " + fileName);
 26:             System.exit(0);
 27:         }
 28: 
 29:         while (inputStream.hasNextLine())
 30:         {
 31:             String line = inputStream.nextLine();
 32:             System.out.println(line);
 33:         }
 34:         inputStream.close();
 35:     }
 36: }