将标准输入的离散块转换为可用形式

Converting disrete chunks of Stdin to usable form

简单地说,如果用户一次性将一大块文本(多行)粘贴到控制台中,我希望能够抓取该块并使用它。

目前我的密码是

val stringLines: List[String] = io.Source.stdin.getLines().toList
doStuff(stringLines)

然而,doStuff 从未被调用过。我意识到 stdin 迭代器没有 'end',但我如何获得当前的输入?我已经检查了很多 SO 答案,但是 none 它们适用于需要整理的多行。我需要一次获得用户输入的所有行,而且它总是作为一个数据粘贴出现。

这是一个粗略的大纲,但似乎可行。我不得不深入研究 Java Executors,这是我以前没有遇到过的,而且我可能没有正确使用它。

您可能想尝试一下超时值,但 10 毫秒通过了我的测试。

import java.util.concurrent.{Callable, Executors, TimeUnit}
import scala.util.{Failure, Success, Try}

def getChunk: List[String] = {  // blocks until StdIn has data
  val executor = Executors.newSingleThreadExecutor()
  val callable = new Callable[String]() {
    def call(): String = io.StdIn.readLine()
  }

  def nextLine(acc: List[String]): List[String] =
    Try {executor.submit(callable).get(10L, TimeUnit.MILLISECONDS)} match {
      case Success(str) => nextLine(str :: acc)
      case Failure(_)   => executor.shutdownNow() // should test for Failure type
                           acc.reverse
    }

  nextLine(List(io.StdIn.readLine()))  // this is the blocking part
}

用法很简单。

val input: List[String] = getChunk