Java Reference
In-Depth Information
The program opens the
Scanner
stream and connects it to the text file
morestuff.txt
as follows:
opening a file
Scanner inputStream =
null
;
...
inputStream =
new
Scanner(
new
FileInputStream("stuff.txt"));
The class
Scanner
, like the classes
PrintWriter
, has no constructor that takes a file
name as its argument, so we need to use another class—in this case, the class
FileInput-
Stream
—to convert the file name to an object that can be a suitable argument to the
Scanner
constructor.
Note that the methods
nextInt
and
nextLine
read from the text files in exactly the
same way as they read from the keyboard. The other
Scanner
methods for reading
input (given in Display 2.6 and repeated in Display 10.6) also behave the same when
reading from a text file as they do when used to read from the keyboard.
Opening a Text File for Reading with
Scanner
You create a stream of the class
Scanner
and connect it to a text file for reading as
follows:
SYNTAX
Scanner
Stream_Object
=
new
Scanner(
new
FileInputStream(
File_Name
));
EXAMPLE
Scanner inputStream =
new
Scanner(
new
FileInputStream("morestuff.txt"));
After this statement, you can use the methods
nextInt
,
nextDouble
,
nextLine
, and so
forth to read from the named text files just as you have used these methods to read from the
keyboard.
When used in this way, the
FileInputStream
constructor, and hence the
Scanner
construc-
tor invocation, can throw a
FileNotFoundException
, which is a kind of
IOException
.
FileNotFoundException
If your program attempts to open a file for reading and there is no such file, then a
FileNot-
FoundException
is thrown. As you saw earlier in this chapter, a
FileNotFoundException
is
also thrown in some other situations. A
FileNotFoundException
is a kind of
IOException
.