Lakshan Sivananthan Lakshan Sivananthan - 4 months ago 32
Groovy Question

Why am I getting a Java IO Exception in this very simple code?

The following is some sample code I created to get myself more familiar with Groovy. I have a good understanding of Java and I am trying to now learn this new language.

class Activity {

static void reverseString() {

def text{

println "Enter a string to be reversed:"
text = it.readLine()

print "\n";
for (int i = text.length() - 1; i >= 0; i--){

print text[i];


static void main(String[] args) {

def selection{

println "Select a project:"
println "1 - Reverse String"
selection = it.readLine()


switch (selection) {

case "1":

I am able to compile and run this code. I am able to enter '1' and press enter, and then the prompt from my method shows up. At this point I am supposed to enter a string to reverse, but before I can enter I get the IO Exception:

Exception in thread "main" Stream closed



at sun.nio.cs.StreamDecoder.readBytes(

at sun.nio.cs.StreamDecoder.implRead(


at sun.nio.cs.StreamDecoder.read0(



at Activity$_reverseString_closure1.doCall(main.groovy:10)

at Activity.reverseString(main.groovy:7)

at Activity.main(main.groovy:39)

What am I missing here?


The purpose of withReader() is to ensure the stream is closed. So after the project selection is input in the main() method, the stream is closed. When reverseString() is executed, it's too late; the stream is closed.

Don't close (directly, or through withReader) . Only close streams that your code creates, not streams that your application receives from a caller, or global instances in the runtime.