How to read from Console in Java

There are different ways user to interact with a system, for example, desktop GUI, CUI, REST API, Web UI and Console. Many users familiar with the GUI or CUI, but more advanced users usually use the console . It's tremendously useful in some cases.

The first one is REPL, means read eval print loop, many dynamic languages support this interface like Clojure, Python, Ruby, Sala, Javascript. For a programmer, REPL is a highly productive way to use a language and do rapid prototyping.

The second application is database administrators, most database product like MySQL, Oracle provide a console that user can manage and maintain the database, you can import export data, run SQL scripts, modify table structures, etc. Oracle even provide a programming language called PLSQL let you programming in it.

Every console application must read input from standard input, when user press Enter, the system will interpret the input and give a feedback to user, usually print to the standard output.

Clojure is a LISP like dynamic programming language built on JVM, it has an awesome REPL, which read Clojure expression from console and evaluate it. It use a PushbackReader that wrapped the System.in to implement the REPL. See How Clojure REPL works.

If you understand how the console application works in Java, you can modify the REPL to suit your needs, for example How to automatically add parentheses in Clojure REPL.

Read character from Console and echo

The example display each char read from Console and it's decimal number. The System.in is line buffered, the read will block until you press Enter. Then the read loop will read characters one by one from the stream and print it to the Console. The EOF is -1, we read it as int, the value should be 65535, this is the loop terminate.

On Windows you can press Ctrl + Z (*nix Ctrl + D) to issue EOF. Or you can kill the JVM by press Ctrl + C.

 
package com.makble.testjava;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class ConsoleExample {
    public static void main(String[] args) throws IOException {
 
        BufferedReader in = new BufferedReader(
                new InputStreamReader(System.in), 1000);
        char ch = 10;
 
        do {
            if (ch == 10) {
 
                System.out.print("Console=>");
                System.out.flush();
            }
            ch = (char) in.read();
            System.out.println("input: " + ch + " number " + (int) ch
                    + "       ");
            System.out.flush();
        } while (ch != 65535);
 
    }
 
}
 
 

You can run it in Eclipse, but it won't set the cursor right. To run it in command line window. Execute

 
java com.makble.testjava.ConsoleExample
 

Read string from Console

Fro command line application, read a string each time is more common in real application. The following example read the whole line from Console and echo it. Press Ctrl + Z to quit.

 
    public static void readConsoleString() throws IOException {
 
        BufferedReader in = new BufferedReader(
                new InputStreamReader(System.in), 1000);
        String str = "";
 
        do {
            if (str == "") {
 
                System.out.print("Console=>");
                System.out.flush();
            }
            str = in.readLine();
            if( str == null) break;
            System.out.println("input: " + str );
            System.out.flush();
            str = "";
        } while (true);
 
    }
 
 

Using a PushbackReader

If you nned to modify the stream then pass the stream to next application for example a parser, you should use a PushbackReader, it allows you read content from the stream and push it back.

 
    public static void pushbackString(PushbackReader in) throws IOException {
        List<Character> chars = new ArrayList<Character>();
        char ch;
        for (;;) {
            ch = (char) in.read();
            if (ch == 10) {
                break;
            }
            if(ch != 13){
                chars.add(ch);
            }
        }
 
        char chs[] = new char[chars.size()];
        for (int i = 0; i < chars.size(); i++) {
            chs[i] = chars.get(i);
        }
 
        String str = new String(chs);
        char[] pushBack = ("(" + str + ")\n").toCharArray();
        in.unread(pushBack);
 
    }
 
    public static void readConsoleStringPushback() throws IOException {
 
        PushbackReader in = new PushbackReader(
                new InputStreamReader(System.in), 1000);
 
        char ch = 10;
 
        do {
            if (ch == 10) {
 
                System.out.print("Console=>");
                System.out.flush();
            }
            ch = (char) in.read();
            in.unread(ch);
            pushbackString(in);
 
            do {
                ch = (char) in.read();
                System.out.println("input: " + ch + " number " + (int) ch
                        + "       ");
                System.out.flush();
 
            } while (ch != 10);
        } while (true);
 
    }
 
 

Output:

 
Console=>hello
input: ( number 40
input: h number 104
input: e number 101
input: l number 108
input: l number 108
input: o number 111
input: ) number 41
input:
 number 10
Console=>