有没有办法用withReader重新打开输入流? - Groovy

时间:2011-11-20 05:35:18

标签: groovy stream system.in

我知道输入流在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

那么实现这一目标的最佳途径是什么?

感谢。

1 个答案:

答案 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

}