Javadoc says why it returns null
console
public static Console console()
Returns the unique Console object associated with the current Java virtual machine, if any.
Returns: The system console, if any, otherwise null.
Since:
1.6
Intellij IDEA returns null too with System.console
so the only thing you can do is to create two methods (one for read line, one for password since System.console have readPassword method) which helps you to avoid problems when switch to IDE to Production.
public static String readLine() throws IOException
{
if (System.console() != null)
{
return System.console().readLine();
}
else
{
return new BufferedReader(new InputStreamReader(System.in)).readLine();
}
}
public static char[] readPassword() throws IOException
{
if (System.console() != null)
{
return System.console().readPassword();
}
else
{
return readLine().toCharArray();
}
}
I chosed to keep the char[] way for readPassword but if you want you can convert it to string.
You can keep in memory the System.console reference to avoid double call to console() method which is syncronized (in my source code at least)
public static String readLine() throws IOException
{
Console console = System.console();
if (console != null)
{
return console.readLine();
}
else
{
return new BufferedReader(new InputStreamReader(System.in)).readLine();
}
}
public static char[] readPassword() throws IOException
{
Console console = System.console();
if (console != null)
{
return console.readPassword();
}
else
{
return readLine().toCharArray();
}
}