1

I know that the input stream is automatically closed at the end of this kind of block in Groovy:

def exec = ""
System.in.withReader {
    println  "input: "
    exec = it.readLine()        
} 

but is there a way to reopen the stream if I want to do something like that:

def exec = ""
while(!exec.equals("q")) {   
    System.in.withReader {
        println  "input: "
        exec = it.readLine()        
    } 
    if(!exec.equals("q")) {
        //do something
    }
}

When I try this I get this error at the second execution of the while loop:

Exception in thread "main" java.io.IOException: Stream closed

So what would be the best way to achieve that?

Thanks.

talnicolas
  • 13,885
  • 7
  • 36
  • 56

1 Answers1

7

You shouldn't try to reopen System.in as you shouldn't close it in the first place. You could try something like the following

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

}
Michael Rutherfurd
  • 13,815
  • 5
  • 29
  • 40