Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

540 Part II: The Java Library


Scanner


Scanneris the complement ofFormatter. Added by JDK 5,Scannerreads 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
ofScanner, 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.
Scannercan be used to read input from the console, a file, a string, or any source that
implements theReadableinterface orReadableByteChannel. For example, you can use
Scannerto read a number from the keyboard and assign its value to a variable. As you will
see, given its power,Scanneris surprisingly easy to use.

The Scanner Constructors

Scannerdefines the constructors shown in Table 18-14. In general, aScannercan be
created for aString, anInputStream, aFile, or any object that implements theReadable
orReadableByteChannelinterfaces. Here are some examples.
The following sequence creates aScannerthat reads the fileTest.txt:

FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);

This works becauseFileReaderimplements theReadableinterface. Thus, the call to the
constructor resolves toScanner(Readable).

Method Description
Scanner(Filefrom)
throws FileNotFoundException

Creates aScannerthat uses the file specified by
fromas a source for input.
Scanner(Filefrom, Stringcharset)
throws FileNotFoundException

Creates aScannerthat uses the file specified byfrom
with the encoding specified bycharsetas a source for
input.
Scanner(InputStreamfrom) Creates aScannerthat uses the stream specified
byfromas a source for input.
Scanner(InputStreamfrom, Stringcharset) Creates aScannerthat uses the stream specified
byfromwith the encoding specified bycharsetas
a source for input.
Scanner(Readablefrom) Creates aScannerthat uses theReadableobject
specified byfromas a source for input.
Scanner (ReadableByteChannelfrom) Creates aScannerthat uses theReadableByteChannel
specified byfromas a source for input.
Scanner(ReadableByteChannelfrom,
Stringcharset)

Creates aScannerthat uses theReadableByteChannel
specified byfromwith the encoding specified bycharset
as a source for input.
Scanner(Stringfrom) Creates aScannerthat uses the string specified by
fromas a source for input.

TABLE 18-14 TheScannerConstructors
Free download pdf