我知道输入流在Groovy中的这种块的末尾自动关闭:
def exec = ""
System.in.withReader {
println "input: "
exec = it.readLine()
}
但如果我想做类似的事情,有没有办法重新打开流:
def exec = ""
while(!exec.equals("q")) {
System.in.withReader {
println "input: "
exec = it.readLine()
}
if(!exec.equals("q")) {
//do something
}
}
当我尝试这个时,我在第二次执行while循环时遇到了这个错误:
Exception in thread "main" java.io.IOException: Stream closed
那么实现这一目标的最佳途径是什么?
感谢。
答案 0 :(得分:6)
您不应该尝试重新打开 System.in ,因为您不应该首先关闭它。你可以尝试类似下面的内容
def exec
def reader = System.in.newReader()
// create new version of readLine that accepts a prompt to remove duplication from the loop
reader.metaClass.readLine = { String prompt -> println prompt ; readLine() }
// process lines until finished
while ((exec = reader.readLine("input: ")) != 'q') {
// do something
}