【问题标题】:How to override stdin to a String如何将标准输入覆盖为字符串
【发布时间】:2016-11-07 19:03:20
【问题描述】:

基本问题,我想将标准输入设置为特定字符串。目前我正在尝试这个:

import java.nio.charset.StandardCharsets
import java.io.ByteArrayInputStream
// Let's say we are inside a method now
val str = "textinputgoeshere"
System.setIn(new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8)))

因为这与我在 Java 中的操作方式相似,但是 str.getBytes 在 Scala 中的工作方式似乎有所不同,因为当我使用 println...检查 System in 时,它被设置为内存地址......

我查看了 Scala API:http://www.scala-lang.org/api/current/scala/Console$.html#setIn(in:java.io.InputStream):Unit 我找到了

def withIn[T](in: InputStream)(thunk: ⇒ T): T

但这似乎只为特定代码块设置输入流,我希望这是我的 JUnit 测试中 Setup 方法中的一个功能。

【问题讨论】:

标签: scala stdin


【解决方案1】:

我的问题最终与我的代码有关,而不是这个特定的概念。在 Scala 中将 Standard In / System In 覆盖为 String 的正确方法如下:

val str = "your string here"
val in: InputStream = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8))
Console.withIn(in)(yourMethod())"

我的测试现在运行正常。

【讨论】:

  • the official scala.Console docs 也涵盖了这个主题,可以使用 java.io.StringReader 作为输入源val input = new StringReader(s"${customStrInput}\n") 或文件内容val input: Reader = openFile( "file.txt" ) 用于Console.withIn( input ) { ... }
猜你喜欢
  • 2018-05-20
  • 2019-09-15
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
  • 2010-10-13
  • 2018-02-04
相关资源
最近更新 更多