5.11.3. Input


Using a scanner to read from the standard input

Input is somewhat awkward to do in Java. There are several different styles, but we only show the java.util.Scanner class here.

To use the scanner class, create a scanner object and then ask that object to perform some operations. I will assume that you have imported java.util.Scanner, as follows.

  import java.util.Scanner;
For example,
  Scanner s = new Scanner(System.in);
  int n = s.nextInt();
  char c = s.nextChar();
The following are some of the methods available in the Scanner class.

s.nextInt()

Read and yield an integer (type int).

s.hasNextInt()

Yields true if there is an integer next.

s.nextLong()

Read and yield an integer (type long).

s.hasNextLong()

Yields true if there is an integer next.

s.nextDouble()

Read and yield a real number (type double).

s.hasNextDouble()

Yields true if there is a real number next.

s.nextLine()

Read and yield an entire line as a string. If part of a line has been read, this returns the remainder of that line.

s.hasNextLine()

Yields true if it is possible to read a line.


Reading from a file or a string

To read from a file, pass the file or the string to new Scanner. For example, if you create Scanner s by

  Scanner s = new Scanner(new File("data.txt"));
then s reads from file data.txt. But if you say
  Scanner t = new Scanner("the rising moon");
then t reads from the given string.


Reading raw characters

A scanner is designed to read tokens, which are, by default, separated by white space. Sometimes you need to read raw bytes. An InputStream object (of which System.in is an example) can do that but it is a little awkward to use. Class java.io.BufferedInputStream is better. If b is a BufferedInputStream then b.read() reads one byte from b and returns it, as an integer (type int).

Expression new BufferedInputStream(System.in) reads from the standard input. See here for an example.

To read from a file, use a FileInputStream, which works much like a BufferedInputStream. Expression new FileInputStream(file-path) creates an object that reads from the file file-path. For example,

  FileInputStream f = new FileInputStream("stuff/data.txt");
  int n = f.read();
Creates an object f that reads from file stuff/data.txt and then reads one byte from f.