Search This Blog

Wednesday, August 10, 2011

How to read input from console (keyboard) in Java?

There are few ways to read input string from your console/keyboard. The following smaple code shows how to read a string from the console/keyboard by using Java.

public class ConsoleReadingDemo {

public static void main(String[] args) {

// ====
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter user name : ");
String username = null;
try {
username = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("You entered : " + username);

// ===== In Java 5, Java.util,Scanner is used for this purpose.
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
username = in.nextLine();
System.out.println("You entered : " + username);


// ====== Java 6
Console console = System.console();
username = console.readLine("Please enter user name : ");
System.out.println("You entered : " + username);

}
}

The last part of code used java.io.Console class. you can not get Console instance from System.Console() when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.

No comments: