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: