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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With