Home : Course Map : Chapter 9 : Java :
Using Scanner for Input from a File
JavaTech
Course Map
Chapter 9

Introduction
Overview
Streams
Wrappers,Buffers
Console I/O
  Text Output 
     Demo 1

  Formatter/printf()
     Demo 2

  Tex 2t Input
     Demo 3

  Scanner
     
Demo 4
File Class
  File I/O
  File Output-Text
     Demo 5

  Formatter to File
     Demo 6

  File Input - Text
    Demo 7

  Scanner - Files
     Demo 8

  File I/O - Binary
     Demo 9
   Demo 10
File Chooser Dialog
  Demo 11

Character Codes
  Demo 12
   Demo13
Object I/O
Types to Bytes
Stream Filters
Other I/O Topics
Exercises

    Supplements
Character I/O
  Demo 1   Demo 2
Random Access
  Demo 3
ZIP/GZIP Streams
  Demo 4
Piped Streams
  Demo 5
NIO Framework
More NIO
  Demo 6

     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

We earlier discussed using the Scanner class to obtain input from the console. can read from a file just as easily as it can from the console. The example program ScanFileApp expects an input file of the type produced by FormatWriteFileApp containing the output shown for FormatWriteApp discussed earlier.

The program uses Scanner to scan past the text at the beginning of the file and then reads each of the primitive type values. There are many options with the pattern matching capabilities of Scanner to jump past the initial text. We choose a simple technique of looking for the first primitive type value, which is a boolean type. So we loop over calls to hasNextBoolean() until we find a boolean value.

This method, and the similar ones for other primitive types, look ahead at the next token and return true or false depending on whether the token is of the type indicated. It does not jump past the token. So, if the next token is not a boolean, we use the next() method to skip this token and examine the next one. When we find the boolean we break out of the loop.

ScanFileApp.java
Resources: textOutput.txt

import java.io.*;
import java.util.*;

/** Demonstrate using Scanner to read a file. **/
public class ScanFileApp
{
  public static void main (String arg[]) {

    File file = null;

    // Get the file from the argument line.
    if (arg.length > 0) file = new File (arg[0]);
    // or use the default
    if (file == null ) {
      file = new File ("textOutput.txt");
    }

    Scanner scanner = null;
    try {
       // Create a scanner to read the file
       scanner = new Scanner (file);
    } catch (FileNotFoundException e) {
      System.out.println ("File not found!");
      // Stop program if no file found
      System.exit (0);
    }

    try {
      // Skip tokens until the boolean is found.
      while (true) {
        if (scanner.hasNextBoolean ()) break;
        scanner.next ();
      }

      System.out.printf ("Skip strings at start of %s %n", file.toString ());
      System.out.printf ("and then read the primitive type values: %n%n");

      // Read and print the boolean
      System.out.printf (" boolean = %9b %n",  scanner.nextBoolean ());

      // and then the set of numbers
      System.out.printf (" int     = %9d %n"  ,scanner.nextInt ());
      System.out.printf (" int     = %9d %n"  ,scanner.nextInt ());
      System.out.printf (" int     = %9d %n"  ,scanner.nextInt ());
      System.out.printf (" long    = %9d %n"  ,scanner.nextLong ());
      System.out.printf (" float   = %9.1f %n",scanner.nextFloat ());
      System.out.printf (" double  = %9.2e %n",scanner.nextFloat ());

    }
    catch (InputMismatchException e) {
      System.out.println ("Mismatch exception:" + e );
    }
  } // main

} // class ScanFileApp

The output of the program goes as:

Skip strings at start of textOutput.txt
and then read the primitive type values:

 boolean = false
 int = 114
 int = 1211
 int = 1234567
 long = 987654321
 float = 983.6
 double = -4.30e-15

 

References and Web Resources

Latest update: March 8, 2006

              Tech
Histogram I/O
Hist I/O - Get/Set
  Demo 1
Hist I/O - Objects
  Demo 2
HistogramStream
  Demo 3
Filtering Data
  Demo 4
Exercises

           Physics
Physics Model
Simulation Design
Physics Simulator
  Demo 1
Experiment Design
Experiment Sim.
  Demo 2
Analysis
Expt. + Analysis
  Demo 3
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.