How do I iterate over all bytes in an inputStream using Groovy, given that it lacks a do-while statement?

末鹿安然 提交于 2019-11-30 17:28:54

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

inputStream.eachByte(BUFFER_SIZE) { buffer, numRead ->
    ...
}

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
}());

use this:

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

    if( numRead == 0 ){ //condition to break, oppossite to while 
        break
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!