15

Given that Groovy does not have a do-while statement, how can I iterate over all bytes in an input stream?

Per a previous version of the Groovy user guide:

No 'do ... while()' syntax as yet.

Due to ambiguity, we've not yet added support for do .. while to Groovy

What would be the best way to do something like the following Java code in Groovy?

def numRead = inputStream.read(fileBytes, 0, fileBytes.length);
do{

} while(numRead > 0);

(I know I can do that using a boolean, I just want to know if there's a "Groovy" way of doing it)

1

3 Answers 3

19

I know that's an old and already answered question. But it's the 1st what pops up for 'groovy do while' when googled.

I think general considerable do-while synonym in Groovy could be:

while ({
    ...

    numRead > 0
}()) continue

Please consider the above example. Except some 'redundant' brackets it's rather well readable syntax.

And here's how does it work:

  1. inside of the while condition round brackets a closure is defined with curly bracket open
  2. the closure gets executed inline with inner round brackets pair after curly bracket close
  3. value of the last line inside the closure is the value which will break the loop when false (it's being returned from the closure)
  4. continue after while condition closing round bracket is only because there has to be 'something', any compilable statement. For example it could be 0, though continue seems to fit much better.

EDIT: Not sure is it a newer version of Groovy or I've missed that before. Instead continue semicolon will do as well. Then it goes like:

while ({
    ...

    numRead > 0
}());
0
14

The groovy (version 1.8+) way would be like this:

inputStream.eachByte(BUFFER_SIZE) { buffer, numRead ->
    ...
}
1
  • @ataylor How can I apply this method to another scenario where BUFFER_SIZE is only known inside the loop? Simply, I don't know the value of BUFFER_SIZE without going inside the loop.
    – biniam
    Apr 18, 2016 at 8:36
2

use this:

for(;;){ // infinite for
    ...

    if( numRead == 0 ){ //condition to break, oppossite to while 
        break
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.