img
Scanner
Scanner is the complement of Formatter. Added by JDK 5, Scanner reads formatted input
and converts it into its binary form. Although it has always been possible to read formatted
input, it required more effort than most programmers would prefer. Because of the addition
of Scanner, it is now easy to read all types of numeric values, strings, and other types of
data, whether it comes from a disk file, the keyboard, or another source.
Scanner can be used to read input from the console, a file, a string, or any source that
implements the Readable interface or ReadableByteChannel. For example, you can use
Scanner to read a number from the keyboard and assign its value to a variable. As you will
see, given its power, Scanner is surprisingly easy to use.
The Scanner Constructors
Scanner defines the constructors shown in Table 18-14. In general, a Scanner can be
created for a String, an InputStream, a File, or any object that implements the Readable
or ReadableByteChannel interfaces. Here are some examples.
The following sequence creates a Scanner that reads the file Test.txt:
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
This works because FileReader implements the Readable interface. Thus, the call to the
constructor resolves to Scanner(Readable).
Method
Description
Scanner(File from)
Creates a Scanner that uses the file specified by
throws FileNotFoundException
from as a source for input.
Scanner(File from, String charset)
Creates a Scanner that uses the file specified by from
throws FileNotFoundException
with the encoding specified by charset as a source for
input.
Scanner(InputStream from)
Creates a Scanner that uses the stream specified
by from as a source for input.
Scanner(InputStream from, String charset) Creates a Scanner that uses the stream specified
by from with the encoding specified by charset as
a source for input.
Scanner(Readable from)
Creates a Scanner that uses the Readable object
specified by from as a source for input.
Scanner (ReadableByteChannel from)
Creates a Scanner that uses the ReadableByteChannel
specified by from as a source for input.
Scanner(ReadableByteChannel from,
Creates a Scanner that uses the ReadableByteChannel
String charset)
specified by from with the encoding specified by charset
as a source for input.
Scanner(String from)
Creates a Scanner that uses the string specified by
from as a source for input.
TABLE 18-14
The Scanner Constructors
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home