Java – Console
To get sensitive user input without echoing it to the console/terminal, the Java SDK has introduced the java.io.Console class. The Console class is quite unique in the way it handles its data. It uses the native encoding of the system instead of the using the JVM’s default encoding.
The Console class provides methods to access the console/terminal, if any is associated with the JVM.
Using the Console class:
So how do you use the Console class ? Its pretty simple really. First get a reference to the Console class from the System class
1 | Console con = System.console(); |
It is not always possible to get a reference to the console. Some scenarios prevent the developer from gaining access to the console. This method may return null in these cases. For example a batch process running on a server will not expect user input and usually does have a console. Your code must be capable of handling such situations.