Scanner creation
In this chapter you will learn:
- Scanner's constructors
- How to create Scanner from FileReader
- How to create Scanner from keyword input
- How to create Scanner from String
Scanner's constructors
Scanner
is the complement of Formatter and reads formatted input.
Scanner can be used to read input from the console, a file, a string, or any source.
The Scanner has the following constructors.
Scanner(String from)
Creates from the stringScanner(File from) throws FileNotFoundException
Creates from the.Scanner(File from, String charset) throws FileNotFoundException
Creates from file with specified encoding.Scanner(InputStream from)
Creates from stream.Scanner(InputStream from, String charset)
Creates from stream with the encoding specifiedScanner(Readable from)
Creates from Readable objectScanner (ReadableByteChannel from)
Creates from ReadableByteChannelScanner(ReadableByteChannel from, String charset)
Creates from ReadableByteChannel with the encoding specified
Create Scanner from FileReader
The following code creates a Scanner that reads the file Test.txt:
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
FileReader implements the Readable interface. Thus, the call to the constructor resolves to Scanner(Readable).
Create Scanner from keyword input
This next line creates a Scanner that reads from standard input, which is the keyboard by default:
Scanner conin = new Scanner(System.in);
System.in is an object of type InputStream. Thus, the call to the constructor maps to Scanner(InputStream).
Create Scanner from String
The next sequence creates a Scanner that reads from a string.
String instr = "1 1.23 this is a test.";
Scanner conin = new Scanner(instr);
Next chapter...
What you will learn in the next chapter:
- How to use Scanner
- Check to see if a certain type of data is available
- Scanner reads the input by one of Scanner's nextX methods.
- Demo code for how to use the hasNext and read next methods
- How to use Scanner to check if there is another line
- How to bypass a pattern