我知道在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
那么实现这一目标的最佳方法是什么呢?
谢谢。
您不应该尝试重新打开系统。在中,因为一开始就不应该关闭它。您可以尝试以下内容
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
}