This java tutorial focuses on the usage of the Scanner class of java.util package. We will be showing the basic usage of Scanner class until the most advanced features of this class using examples. As we move along on this document, we will be showing java scanner examples more importantly on the usage of Scanner methods.
The Scanner class has a rich set of API which generally used to break down the input to Scanner constructor into tokens. It can parse the tokens into primitive data types using java regular expressions. The input is broke down into tokens using the delimiter defined on the Scanner class using the radix method or can be define as well as method argument on some of the methods available on this scanner class.
Scanner Class Declaration
public final class Scanner
implements Iterator, Closeable
Scanner Class Constructors
public Scanner(Readable source)
Constructs a new Scanner that produces values scanned from the specified source.
source – A character source implementing the Readable interface
Don’t get confused on the Object type Readable as constructor parameter. Readable is an interface which has been implemented by BufferedReader, CharArrayReader, CharBuffer, FileReader, FilterReader, InputStreamReader, LineNumberReader, PipedReader, PushbackReader, Reader, StringReader. Which means, we can use any of these classes in instantiating the Scanner object.
Constructs a new Scanner that produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the underlying platform’s default charset.
source – An input stream to be scanned
The method input on this constructor is InputStream. The InputStream class is one of the top level classes in the java.io package and using it would be a problem. However we can use the subclasses of InputStream as shown below. We have used the FileInputStream for below example as it is a subclass of InputStream, there would not be an issue in using it.
public Scanner(File source) throws FileNotFoundException
Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform’s default charset.
source – A file to be scanned
This constructor is very straightforward. It just require a File source. So it means that this constructor sole purpose is instantiate a Scanner object to scan through a File.