Unable to use java/groovy console while debugging

I have a very simple groovy script that reads a username and password from the console. If I run the script from the command line it works perfectly. However, if I try to run it from within Intellij, the console is null.

How can I read console input while debugging my script?

String username
String password

def console = System.console()
if (console) {
    username = console.readLine('> Please enter your username: ')
    password = new String(console.readPassword('> Please enter your password: '))
    println "username: ${username} password: ${password}"
} else {
    println "Cannot get console, exiting..."
    System.exit(1)
}

1 comment
Comment actions Permalink

System.console()
will return null if launched from the IDE. This is IDE limitation. See the documentation http://docs.oracle.com/javase/7/docs/api/java/io/Console.html :

If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.
If this virtual machine has a console then it is represented by a unique instance of this class which can be obtained by invoking the System.console() method. If no console device is available then an invocation of that method will return null.

Try to avoid using System.console or launch from the command line and attach to the process using remote debug. Please check this thread for some  solutions http://stackoverflow.com/questions/4203646/system-console-returns-null . See corresponding issue in our tracker http://youtrack.jetbrains.com/issue/IDEABKL-5949 .

0

Please sign in to leave a comment.