Java: How to get input from System.console()
I am trying to use Console class to get input from user but a null object is returned when I call System.console()
. Do I have to change anything before using System.console?
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
Using Console to read input (usable only outside of an IDE):
System.out.print("Enter something:");
String input = System.console().readLine();
Another way (works everywhere):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
System.out.print("Enter Integer:");
try {
int i = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe) {
System.err.println("Invalid Format!");
}
}
}
System.console() returns null in an IDE.
So if you really need to use System.console()
, read this solution from McDowell.
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String s = in.next();
There are few ways to read input string from your console/keyboard. The following sample 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.