Java Reference
In-Depth Information
Note that we close the stream explicitly. For this short program that ends very
soon after finishing the read, closing the input stream is not so important, but in
general, it is good practice to always close input and output streams for files when
I/O transfers are completed.
9.6.4 Input from a file with
Scanner
The
Scanner
class, discussed in Section 9.4.4, 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
FormatWriteApp
(see Section 9.6.2) containing
the output as shown for
FormatWriteAppFile
(see Section 9.4.2). It uses
Scanner
to scan past the text at the beginning of the file and then it 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
. 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
,weuse the
next()
method to
skip this token and examine the next one. When we find the
boolean
we break
out of the loop.
import java.io.*;
import java.util.*;
/** Demonstrate using Scanner to read a file. **/
public class
ScanFileApp
{
public static void main (String[] args) {
File file = null;
// Get the file from the argument line.
if (args.length > 0) file = new File (args[0]);
// or use the default
if (file
==
null)
{
file
=
new File (
"
textOutput.txt
"
);
}
Scanner scanner
=
null;
try
{
// Create a scanner to read the file
Search WWH ::
Custom Search