Scanner creation

In this chapter you will learn:

  1. Scanner's constructors
  2. How to create Scanner from FileReader
  3. How to create Scanner from keyword input
  4. 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 string
  • Scanner(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 specified
  • Scanner(Readable from)
    Creates from Readable object
  • Scanner (ReadableByteChannel from)
    Creates from ReadableByteChannel
  • Scanner(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:

  1. How to use Scanner
  2. Check to see if a certain type of data is available
  3. Scanner reads the input by one of Scanner's nextX methods.
  4. Demo code for how to use the hasNext and read next methods
  5. How to use Scanner to check if there is another line
  6. How to bypass a pattern
Home » Java Tutorial » I/O
RandomAccessFile
FilenameFilter
StreamTokenizer
Console
Console password reading
Scanner creation
Scanner read and scan
Scanner Delimiters
Scanner finding