How to read input from console with Java

In this tutorial we show you how to read input from console with Java.

  1. java.io.BufferedReader wrapped in a java.io.InputStreamReader
  2. java.util.Scanner

BufferedReader wrapped in a InputStreamReader

The System.in is the standard input stream this stream is default open and is typically used for keyboard input. We wrap the stream in a InputStreamReader which reads the stream by the specified charset. Then we wrap this stream in a BufferedReader which’ll read line until the text equals to “goodbye”. The readLine() method can throw a IOException.

package com.memorynotfound;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadConsoleSystem {

    public static void main(String[] args) throws IOException {
        String text;
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in, Charset.forName("UTF-8")));
        System.out.println("Enter input: ");
        do {
            text = bufferRead.readLine();
            System.out.println("response: " + text);
        } while (!"goodbye".equalsIgnoreCase(text));

    }

}

java.util.Scanner

Personally I prefer the java.util.Scanner class. The nextLine() method does not throw a CheckedException. And is much more intuitive to use. The java.util.Scanner class was introduced in JDK 1.5.

package com.memorynotfound;

import java.util.Scanner;

public class ReadConsoleScanner {

    public static void main(String[] args) {
        Scanner scanIn = new Scanner(System.in);
        String text;
        System.out.println("Enter input: ");
        do {
            text = scanIn.nextLine();
            System.out.println("response: " + text);
        } while (!"goodbye".equalsIgnoreCase(text));
        scanIn.close();
    }

}

Read input from console example output

Both applications do the same thing, here is a sample output.

Enter input: 
Can you tell me how to read input from console?
response: Can you tell me how to read input from console?
No
response: No
Goodbye
response: Goodbye

References

You may also like...