Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading password from console in Scala

Tags:

input

scala

In a Scala program I need to read from the standard input a password string (with echoing disabled). I tried with:

java.io.Console.readPassword

But for some reason I cannot invoke any methods in the java.io.Console object from Scala (?).

Which is the "standard" way to read a string (with echoing disabled) from the standard input in Scala ?

like image 885
Sergio Avatar asked Oct 30 '12 19:10

Sergio


1 Answers

I assume you want to read the password from the console prompt, so you will need to create a Console instance from the System (Console is not a singleton).

scala> val standardIn = System.console()
standardIn: java.io.Console = java.io.Console@69d1964d

scala> val password = standardIn.readPassword()

Note that no import is necessary because of Scala's type inference and the fact that System is already in scope by default.

Consult the javadoc for java.io.Console for more info.

EDIT: In a compiled Scala program:

object ReadPassword {
  def main(args: Array[String]) {
    val standardIn = System.console()
    println("standardIn object: " + standardIn)

    print("Password> ")
    val pw = standardIn.readPassword()

    print("Password: ")
    pw.foreach(print) // For demonstration purposes
    println()
  }
}

Compiling/running:

$ scalac ReadPassword.scala
$ scala ReadPassword
standardIn object: java.io.Console@311671b2
Password> 
Password: hello world
like image 154
adelbertc Avatar answered Oct 16 '22 15:10

adelbertc