Java Reference
In-Depth Information
Solution
Use the Java 6 System.console() method to obtain a Console object, and use its methods.
Discussion
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 de-
fault. However, the standard input can be changed by piping or redirection on most OSes. If
you really want to read from “wherever the user is sitting,” bypassing any indirections, then
the Console class is usually your friend.
You cannot instantiate Console yourself; you must get an instance from the System class's
console() method. You can then call methods such as readLine() , which behaves largely
like the method of the same name in the BufferedReader class used in the previous recipe.
The following code shows an example of prompting for a name and reading it from the con-
sole:
src/main/java/io/ConsoleRead.java
public
public class
class ConsoleRead
ConsoleRead {
public
public static
void main ( String [] args ) {
String name = System . console (). readLine ( "What is your name?" );
System . out . println ( "Hello, " + name . toUpperCase ());
static void
}
}
One complication is that 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 production-quality
code should always check for null before trying to use the Console . If you do get null , you
can fall back to using the code in Reading Standard Input .
One facility the Console class is quite useful for is reading a password without having it
echo. This has been a standard facility of command-line applications for decades, as the most
obvious way of preventing “shoulder surfing”—looking over your shoulder to see your pass-
word. Nonecho password reading is now supported in Java: the Console class has a
readPassword() method that takes a prompt argument, intended to be used like:
Search WWH ::




Custom Search