com.genedavis.io.SystemInputReader

I wrote my SystemInputReader¬†sometime around 2001. There are easier ways of doing this now, but I know some people used to find it helpful, so I’m re-posting it here. Scroll down past the old example to see the new way of getting console input.

The SystemInputReader class contains a method for reading the next line of text from the keyboard as a String. It does block waiting for a return, so if your program needs to be doing other stuff, throw this into a separate Thread.

package com.genedavis.io;

import java.io.*;

/**
 * SystemInputReader.java
 * Created by Gene Davis on Sat Aug 18 2001.
 * 
 * version 1.0
 */
public class SystemInputReader {
	BufferedReader keyboardInput = null;
	String newLine = null;
	/**
	 * Creates new SystemInputReader 
	 */
	public SystemInputReader() {
	    keyboardInput = new BufferedReader(new InputStreamReader(System.in));
	}

	/**
	 * This retrieves text one line at a time from the keyboard and returns 
	 * a line at a time as a String. This will block until the user types 
	 * and enters a line with or without text. I usually tack a String.trim()
	 * on to the end of the return before using it.
	 *
	 * @param String representing a new line of text inputed from the keyboard.
	 */
	public String nextLine() {
	    try {
	        newLine = keyboardInput.readLine();
	    } catch (Exception e){
	        e.printStackTrace();
	    }
	    return newLine;
	}
}

Now that was all fine and dandy, circa 2001, when Java Swing was still considered cutting edge. Java has grown up a bit since then, and in Java 6 added the java.io.Console class and the java.util.Scanner class. Console is useful when dealing with an actual console, but from inside an IDE such as Eclipse, the Scanner class is more useful.

The easiest way to create a scanner is to construct it with System.in. Then, call your scanner’s nextLine() method to get a full line of input. Here is the full example.

package com.tgenedavis;

import java.util.Scanner;

/**
 * Creates a separate thread to capture console input using a Scanner object.
 * This code uses a Lambda Function, so requires Java 8 or newer.
 */
public class ConsoleExample {

	private static Runnable readingRunnable = () -> {
		boolean stayingAlive = true;

		// constructing the Scanner with System.in
		// System.in is the console input
		Scanner scanner = new Scanner(System.in);

		String oneLineOfText;

		while (stayingAlive) {
			System.out.print(">");

			// grabbing the next line of user input
			oneLineOfText = scanner.nextLine();

			if ("quit".equals(oneLineOfText)) {
				stayingAlive = false;
			}
		}
		System.out.println("quiting ... ");

		scanner.close();
	};

	public static void main(String[] args) {

		// everything starts here
		Thread t = new Thread(readingRunnable);
		t.start();

	}

}