previous | start | next

Creating a Scanner associated with a File

import java.util.Scanner;

    1   public static void main(String[] args) {
    2       String fileName;
    3       Scanner input = new Scanner(System.in);
    4       Scanner infile = null;
    5       int max = 0, n;
    6       
    7       System.out.println("This program will read integers (negative, non-negative) and print the largest value.");

   10       fileName = input.next();
   11       
   12       // Try to create a Scanner for the file name entered
   13       try {
   14         infile = new Scanner(new File(fileName));
   15       } catch(FileNotFoundException e) {
   16         System.out.printf("Unable to open input file %s\n", fileName);
   17         System.exit(1);
   18       }
   19       ...
   20   }


previous | start | next