scala 在intellij中运行scala程序时模拟来自stdin的输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18437181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simulate input from stdin when running a scala program in intellij
提问by javadba
Is there any way to configure the command line args to intellij for stdin redirection?
有什么方法可以将命令行参数配置为 intellij 以进行 stdin 重定向?
Something along the lines of:
类似的东西:
Run | Edit Run Configurations | Script Parameters
运行 | 编辑运行配置 | 脚本参数
/shared/java/paf-rules.properties 2 < /shared/java/testdata.csv
采纳答案by javadba
Here is a template for a solution that has options for:
这是一个解决方案模板,其中包含以下选项:
- stdin
- file
- "heredoc" within the program (most likely useful for testing)
- 标准输入
- 文件
- 程序中的“heredoc”(最有可能对测试有用)
.
.
val input = """ Some string for testing ... """
def main(args: Array[String]) {
val is = if (args.length >= 1) {
if (args(0) == "testdata") {
new StringInputStream(input)
} else {
new FileInputStream(args(0))
}
} else {
System.in
}
import scala.io._
Source.fromInputStream(is).getLines.foreach { line =>
This snippet requires use of a StringInputStream - and here it is:
此代码段需要使用 StringInputStream - 这里是:
class StringInputStream(str : String) extends InputStream {
var ptr = 0
var len = str.length
override def read(): Int = {
if (ptr < len) {
ptr+=1
str.charAt(ptr-1)
} else {
-1
}
}
}
回答by vikingsteve
Unfortunately, no - at least not directly in run configurations.
不幸的是,没有 - 至少不是直接在运行配置中。
The best you can do, afaik, is either to:
你能做的最好的事情就是:
modify your script / program to run either with no args (reads
System.in) or with a filename argument (reads the file)make a wrapper script / program which acts in the manner above.
修改您的脚本/程序以在没有参数(读取
System.in)或使用文件名参数(读取文件)的情况下运行制作一个以上述方式运行的包装脚本/程序。
Hope this helps,
希望这可以帮助,
vikingsteve
维京史蒂夫

