Read contents from console or command line (Scanner/ Java/ Example)

By | January 5, 2017
  • Scanner class is a text parser, which is used to parse primitives & strings using regular expression.
  • Scanner split the input into token using delimiter pattern.
    • Default delimiter pattern is a whitespace.
  • We will read the contents from console or command line using Scanner class.
  • Scanner class extends object & implements Closeable & Iterable interface.

1. Class hierarchy of Scanner class:

scanner read write console

Fig: Scanner class hierarchy

2. Read contents from console/command line in java (scanner/example)

package org.learn.io.scan;

import java.io.IOException;
import java.util.Scanner;

public class ReadConsoleUsingScanner {

    public static void main(String[] args) throws IOException {
        System.out.println("Enter value on console:");
        try (Scanner scanner = new Scanner(System.in)) {
            while (scanner.hasNext()) {
                if (scanner.hasNextInt()) {
                    System.out.println("Integer value from console : " + scanner.nextInt());
                } else if (scanner.hasNextDouble()) {
                    System.out.println("Double value from console : " + scanner.nextDouble());
                } else if (scanner.hasNext()) {
                    String input = scanner.next();
                    if (input.equals("complete")) {
                        System.out.println("Successfully read contents from console");
                        //Successfully read input from console
                        break;
                    } else {
                        System.out.println("String value from console : " + input);
                    }
                }
            }
        }
    }
}

3. OP: read contents from console/command line (java/scanner/example)

Enter value on console:
25
Integer value from console : 25
63.24
Double value from console : 63.24
ConsoleReader
String value from console : ConsoleReader
complete
Successfully read contents from console