Lakshan Sivananthan Lakshan Sivananthan - 2 months ago 23
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

System.in.withReader{

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

System.in.withReader{

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

}

switch (selection) {

case "1":
reverseString()
break
}
}
}


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" java.io.IOException: Stream closed

at java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:170)

at java.io.BufferedInputStream.read(BufferedInputStream.java:336)

at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)

at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)

at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)

at sun.nio.cs.StreamDecoder.read0(StreamDecoder.java:127)

at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:112)

at java.io.InputStreamReader.read(InputStreamReader.java:168)

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?

Answer

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 System.in (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.

Comments