1

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

那么实现这一目标的最佳方法是什么?

谢谢。

4

1 回答 1

7

您不应该尝试重新打开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

}
于 2011-11-20T07:28:49.060 回答