Reputation: 33
I'm trying to make a Java program more "Groovy". The java code reads an InputStream like so:
static int myFunction(InputStream is) throws IOException {
int b=is.read();
if (b==0) return b;
StringBuffer sb=new StringBuffer();
int c;
boolean done = false;
while(!done) {
c=is.read();
sb.append((char)c);
if(c == '\n') {
done=true;
}
}
System.out.println(sb.toString());
if (b == 1) throw new IOException("blah");
return b;
}
My Groovy version looks like this:
def myFunction(InputStream is) throws IOException {
int b=is.read()
if (b==0) return b
def reader = new BufferedReader(new InputStreamReader(is))
reader.eachLine { println(it) }
println("DONE")
if (b == 1) throw new IOException("blah")
return b
}
It prints the contents of the stream and then just hangs as if it's trying to read more. It never prints "DONE" (added for debugging). Next I tried it using is.eachByte and passing a closure with an explicit "if (c == '\n') return" but I found that return inside a closure acts more like a continue and doesn't actually break out of the closure. Any idea what I'm doing wrong?
Upvotes: 1
Views: 4061
Reputation: 171104
Instead of
reader.eachLine { println(it) }
Can you try
println reader.readLine()
Upvotes: 1