Java Reference
In-Depth Information
22.5.
Scanner
The
Scanner
class will help you read files of formatted data, such as those
you might generate from a method that used
printf
. It uses regular ex-
pressions to locate the desired data, and parsers to convert them into
known types. For example, it knows how to use localized number parsing
to read in values that humans might type (such as "20,352").
Many of the methods of
Scanner
can take a pattern to indicate how the
scanner should match input. These methods all have two overloaded
forms: One takes the pattern as a
String
and the other takes it as a
java.util.regex.Pattern
.When we say that a method takes a pattern, you
should infer from this that there are two variants of the method as just
described. Supplying a pattern as a string may require that it be com-
piled each time (using
Pattern.compile
), so if a pattern is to be reused it
on page
321
for a refresher on regular expression patterns.
There are two primary approaches to using
Scanner
, although they can be
reasonably intermixed as desired, with care. The first is to use it to read
a stream of values. The second is line-oriented.
22.5.1. Stream of Values
When reading input as a stream of values, you simply ask
Scanner
to re-
turn the next value in the stream. The scanner determines the next value
by first skipping over any delimiter characters in the input (which by de-
fault matches whitespace) and examining the input up to the next delim-
iter. For example, the following code is a rewrite of the
sumStream
example
static double sumStream(Readable source) throws IOException {
Scanner in = new Scanner(source);
double result = 0.0;
while (in.hasNext()) {
if (in.hasNextDouble())