15.6. Using a Scanner
The java.util.Scanner class defines objects that use regular expressions to scan character input from a variety of sources and present the input as a sequence of tokens of various primitive types or as strings. For example, you can use a Scanner object to read data values of various types from a file or a stream, including the standard stream System.in. Indeed, using a Scanner object would have saved you the trouble of developing the FomattedInput class back in Chapter 8—still, it was good practice, wasn't it?
The facilities provided by the Scanner class are quite extensive, so I won't be able to go into all of it in detail because of space limitations. I'll just provide you with an idea of how the scanner mechanisms you are likely to find most useful can be applied. Once you have a grasp of the basics, I'm sure you'll find the other facilities quite easy to use.
15.6.1. Creating Scanner Objects
You can create a Scanner object by passing an object encapsulating the source of the data to be scanned to a Scanner constructor. You have five overloaded Scanner constructors that accept a single argument of any of the following types:
InputStream File ReadableByteChannel Readable String
The Scanner object that is created will be 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, FileReader, InputStreamReader, and a number of other readers, ...
Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.