The less known API for Console input in Java

The less known API for Console input in Java

·

2 min read

These days with the presence of numerous GUI based and Web based apps, receiving input and data via console has reduced. However, there are applications that require and run in a console. Java applications are not an exception to this.

Getting input from the user was not as simple in Java as in other languages like scanf in C, cin in C++ and the input() method in Python. In the early days one had to write code like this

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.read(...)

The BufferedReader construct is itself enough to scare the newbie programmer of Java.

However, from Java 6 - yes you heard me Java 6 - we had a new API that made getting console input much easier, but the programmer world mostly stuck to the old way and this was least known.

String input = System.console().readLine();

which is less scary than the previous one. In addition it also provides a C like format string based input reading as well for interactive input, so you could do something like

Console console = System.console();
String name = console.readLine("Please enter your name: ");
System.console().readLine("Where do you live %s?", name);

When we run the code, we would see something like this

Please enter your name: Gordon
Where do you live Gordon?:

The other wonderful method of the console class is the readPassword() that enables to receive a password from the user with the echo disabled when the user types the password.

The Console class also provides the Reader object to read the usual way and also the Writer object. However, the catch is that it requires a terminal to run the main program. If it is run by a background task, the System.console() method returns null.

Happy coding!

Image Credits: Pixabay