Thursday, 2 October 2014

When ever you want to install a package / software from terminal in Linux based machines, you have to enter super user's password. If you observe, while entering your password, you can't see what you are typing. Here the terminal is not echoing what you have entered. You can do the same in java also, using Console class.

The Console class is intended for reading directly from a program's controlling terminal. When you run an application from a "terminal window" or "command prompt window" on most systems, its console and its standard input are both connected to the terminal, by default.

You cannot create an object of Console yourself. For this, call System.console() method,which gives a Console Object, then you can call methods such as readLine(), which behaves same as method readLine() from BuferredReader class.

The System.console() method can return null if the console isn't connected. Annoyingly, some IDEs including Eclipse don't manage to set up a controlling terminal when you use the Run As -> Java Application mechanism. So while writing production code, you should always check for null before trying to use the console.

Reading Password Without Echoing :

Reading password without having it echo, is the standard facility of command line applications for decades. If you want to provide this feature in java, use readPassword() method of Console class. This method returns an array of bytes, which can be used directly in some encryption and security APIs, or can be easily converted into a String.

It is generally advised to overwrite the byte array after use to prevent security leaks when other code can access the stack. Program

When i ran this program from eclipse, i got null pointer exception, because the console is not connected to the console of Eclipse window, resulting console object to be null.The above output is when i ran the code from command prompt.