Java Reference
In-Depth Information
Display 10.3
Reading Input from a Text File Using
Scanner
(part 2 of 2)
S
CREEN
O
UTPUT
I will read three numbers and a line
of text from the file morestuff.txt.
The three numbers read from the file are:
1, 2, and 3
The line read from the file is:
Eat my shorts.
Testing for the End of a Text File with
Scanner
When using the class
Scanner
, if your program tries to read beyond the end of the file
with any of the input methods, such as
nextInt
or
nextLine
, then the method throws
an exception. If all goes well and there are no problems, such as using
nextInt
when the
input is not a correctly formed
int
, then the exception thrown will be
NoSuchElement-
Exception
. This throwing of a
NoSuchElementException
can be used to signal the
end of input. However, there is a more robust way of testing for the end of input
from a text file. Each of the input methods, such as
nextInt
and
nextLine
, has a
corresponding method, such
hasNextInt
and
hasNextLine
, that checks to see if
there is any more well-formed input of the appropriate type. The nice thing
about these methods is that they report when there is not a suitable next token
for any reason; they do not check only for the end of a file. For example,
hasNextInt
returns
false
if there is no more file input of any kind or if the next
token is not a well-formed
int
value. It returns
true
if there is a well-formed
int
as the next token.
A sample program that illustrates the use of
hasNextLine
to test for the end of
input is given in Display 10.4. A sample program that illustrates the use of
hasNextInt
to test for the end of input is given in Display 10.5. A summary of some of the meth-
ods in the
Scanner
class is given in Display 10.6.
Checking for the End of a Text File with
Scanner
You can check for the end of input with methods such as
hasNextInt
,
hasNextLine
, and
so forth.