Java Reference
In-Depth Information
the standard stream System.in . Indeed, using a Scanner object would have saved you the trouble of devel-
oping the FormattedInput class in Chapter 8 — still, it was good practice, wasn't it?
The facilities provided by the Scanner class are quite extensive, so I'm not able to go into all of it in
detail because of space limitations. I just provide you with an idea of how the scanner mechanisms you are
likely to find most useful can be applied. After you have a grasp of the basics, I'm sure you'll find the other
facilities quite easy to use.
Creating Scanner Objects
A Scanner object can scan a source of text and parse it into tokens using regular expressions. You can create
a Scanner object by passing an object that encapsulates the source of the data to a Scanner constructor. You
can construct a Scanner from any of the following types:
InputStream File Path ReadableByteChannel Readable String
The Scanner object that is created is able to read data from whichever source you supply as the argument
to the constructor. Readable is an interface implemented by objects of type such as BufferedReader ,
CharBuffer , InputStreamReader , and a number of other readers, so you can create a Scanner object that
scans any of these. For input from an external source, such as an InputStream or a file identified by a Path
object or a File object, bytes are converted into characters either using the default charset in effect or using
a charset that you specify as a second argument to the constructor.
Of course, read operations for Readable sources may also result in an IOException being thrown. If this
occurs, the Scanner object interprets this as signaling that the end of input has been reached and does not
rethrow the exception. You can test whether an IOException has been thrown when reading from a source
by calling the ioException() method for the Scanner object; the method returns the exception object if the
source has thrown an IOException .
Let's take the obvious example of a source from which you might want to interpret data. To obtain a
Scanner object that scans input from the keyboard, you could use the following statement:
java.util.Scanner keyboard = new java.util.Scanner(System.in);
Creating a Scanner object to read from a file is a little more laborious because of the exception that might
be thrown:
Path file = Paths.get("TryScanner.java");
try (Scanner fileScan = new Scanner(file)){
// Scan the input...
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
}
This creates a Scanner object that you can use to scan the file TryScanner.java . The Scanner class
implements AutoClosable so you can create it in the form of a try block with resources.
Getting Input from a Scanner
Search WWH ::




Custom Search