我无法从您的问题中判断您是否打算让用户向控制台提供除标准输入以外的其他输入。虽然我怀疑您希望它“完全包含”在 Scala 程序中,但我还没有解决这个问题。然而,如果使用控制台是可以接受的,这里有一个简单的 Scala 程序示例,它要求输入用户名/密码,另一个 Scala 程序启动它并使用Process.run(true) 将调用程序的 out/err 连接到控制台,而输入可以提供给控制台。
SimpleProgram 用于测试输入:
package so
import java.util.Scanner
object SimpleProgram extends App {
def getInput(prompt: String): Option[String] = {
print( s"$prompt: " )
val sc = new Scanner(System.in)
sc.hasNextLine match {
case true => val out = sc.nextLine
if( out.length > 1 ) Some(out) else None
case _ => None
}
}
while( true ) {
(getInput("username"), getInput("password")) match {
case (Some(u), Some(p)) => println( s"Logged in as $u" ); System.exit(0)
case _ => println( "Invalid input. Please try again." )
}
}
}
这是调用 ProcessBuilder 的程序(类路径在没有更改的情况下无法工作):
package so
import scala.sys.process._
object ProcessBuilderTest extends App {
val classpath = "<path to>/scala-library.jar:./classes"
val pb = Process("java", Seq("-cp", classpath, "so.SimpleProgram" ))
pb.run(true) // all the magic happens here.
}
在这种情况下,Process 基本上只是将调用的程序包装在ProcessBuilder 中。我无法使用 ProcessIO 和提供的方法来解决问题,既吃掉适当的字符,又杀死流等。我的猜测是,查看工作中的 run(true) 案例会很有启发性。
以下是控制台日志记录的示例,该示例使用更正的类路径运行后者:
username: foo
password:
Invalid input. Please try again.
username: foo
password: bar
Logged in as foo
我正在使用“java”来运行 Scala 代码,因为除了通过 Eclipse 之外,我的 Mac 上没有安装 Scala。在 Eclipse 中,ProcessBuilderTest 是从项目目录中运行的,其中包含两个类,并且输出目录设置为“classes”而不是“bin”。