previous | start | next

Scanner Input from a File:

To count and find the maximum of integers in an input file, we need to first set up the Scanner.

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

    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 from a file and print the largest value.");
    8       System.out.printf("\nEnter the input file name: ");
    9       
   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