Java Reference
In-Depth Information
Continued from previous page
The line of code may seem correct because it mentions the name of the file,
but it won't work because it doesn't include the
File
object.
Normally, when you make a mistake like this Java warns you that you have
done something illegal. In this case, however, you'll get no warning from Java.
This is because, as you'll see later in this chapter, it is possible to construct a
Scanner
from a
String
, in which case Java reads from the
String
itself.
If you were to make this mistake in the
CountWords
program, you would get
the following output:
total words = 1
The program would report just one word because the
String "hamlet.txt"
looks like a single word to the
Scanner
. So, whenever you construct a
Scanner
that is supposed to read from an input file, make sure that you include the call on
new File
to construct an appropriate
File
object.
Now that we've introduced some of the basic issues involved in reading an input file, let's
explore reading from a file in more detail. One way to process a file is token by token.
Token-Based Processing
Processing input token by token (i.e., one word at a time or one number at
a time).
Recall from Chapter 3 the primary token-reading methods for the
Scanner
class:
•
nextInt
for reading an
int
value
•
nextDouble
for reading a
double
value
•
next
for reading the next token as a
String
For example, you might want to create a file called
numbers.dat
with the follow-
ing content:
308.2 14.9 7.4
2.8
3.9 4.7 -15.4
2.8
Search WWH ::
Custom Search