How to write a command-line or terminal application that will accept user input from the keyboard in Java.
Make use of the java.io.BufferedReader and java.io.InputStreamReader classes to read keyboard entry and store it into local variables. Listing 1-8 shows a program that will keep prompting for input until you enter some characters that represent a valid value of type long.
Listing 1-8. Keyboard Input and Exception Handling
package org.java9recipes.chapter01.recipe1_11;
import java.io.*;
public class AcceptingInput {
public static void main(String[] args){
BufferedReader readIn = new BufferedReader(
new InputStreamReader(System.in)
);
String numberAsString = "";
long numberAsLong = 0;
boolean numberIsValid = false;
do {
/* Ask the user for a number. */
System.out.println("Please enter a number: ");
try {
numberAsString = readIn.readLine();
System.out.println("You entered " + numberAsString);
} catch (IOException ex){
System.out.println(ex);
}
/* Convert the number into binary form. */
try {
numberAsLong = Long.parseLong(numberAsString);
numberIsValid = true;
} catch (NumberFormatException nfe) {
System.out.println ("Not a number!");
}
} while (numberIsValid == false);
}
}
Following is an example run of this program:
Please enter a number:
No
You entered No
Not a number!
Please enter a number:
Yes
You entered Yes
Not a number!
Please enter a number:
42
You entered 42
BUILD SUCCESSFUL (total time: 11 seconds)
The first two inputs did not represent valid values in the long data type. The third value was valid, and the run ended.
How It Works
Quite often our applications need to accept user input of some kind. Granted, most applications are not used from the command line or terminal nowadays, but having the ability to create an application that reads input from the command line or terminal helps to lay a good foundation, and may be useful in some applications or scripts. Terminal input can also be useful in developing administrative applications that yo or a system administrator may use.
Two helper classes were used in the solution to this recipe. They are java.io.BufferedReader and java.io.InputStreamReader. The early portion of the code that’s using those classes is especially important to understand:
BufferedReader readIn = new BufferedReader(
new InputStreamReader(System.in)
);
The innermost object in this statement is System.in. It represents the keyboard. You do not need todeclare System.in. Java’s runtime environment creates the object for you. It is simply available to be used.
System.in provides access to raw bytes of data from the input device, which is the keyboard in our example. It is the job of the InputStreamReader class to take those bytes and convert them into characters in your current character set. System.in is passed to the InputStreamReader() constructor to create an InputStreamReader object.
InputStreamReader knows about characters, but not about lines. It is the BufferedReader class’s job to detect line breaks in the input stream, and to enable you to conveniently read a line at a time.
BufferedReader also aids efficiency by allowing physical reads from the input device to be done in different-size chunks than by which your application consumes the data. This aspect can make a difference when the input stream is a large file rather than the keyboard.
Following is how the program in Listing 1-8 makes use of an instance (named readIn) of the BufferedReader class to read a line of input from the keyboard:
numberAsString = readIn.readLine();
Executing this statement triggers the following sequence:
I/O calls must be wrapped in try-catch blocks. These blocks are used to catch any exceptions that may occur. The try part in the example will fail in the event a conversion is unsuccessful. A failure prevents the numberIsValid flag from being set to true, which causes the do loop to make another iteration so that the user can try again at entering a valid value. To learn more about catching exceptions,
The following statement at the top of Listing 1-8 deserves some mention:
import java.io.*;
This statement makes available the classes and methods defined in the java.io package. These include InputStreamReader and BufferedReader. Also included is the IOException class used in the first try-catch block.