2011-11-20 54 views
1

我知道输入流在这种块在Groovy结束时自动关闭:有没有办法用withReader重新打开输入流? - 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 

那么这将是一个最好的方式那么?

谢谢。

回答

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 

} 
+0

对不起,延迟,刚回来的代码今天测试。好的,谢谢! – talnicolas

相关问题