More elegant stream reading stream?

For many years, I read from InputStreams in a loop as follows:

final byte[] buffer = new byte[65536];
InputStream is = ...;
int r;
while ((r = is.read(buffer)) > 0) {
    ...
}

But I wonder if there is a way to avoid this assignment in the loop (without introducing the second condition) - for example. I find this code even less elegant since there are two read statements and two conditions:

r = is.read(buffer);
if (r > 0) {
  do {
      ...
      r = is.read(buffer);
  } while (r > 0);
}

Any ideas for a more elegant (compact, without conditional) design?

+5
source share
4 answers

What do you think about this:

for (int count = stream.read(buffer); count >= 0; count = stream.read(buffer)) {
  .....
}

it is compact and retains the smallest possible size of the count variable, but it can be considered less readable

+5
source

IMO, the first one is the best and most compact. :)

+4
source

do {} while() .

( ):

int count = stream.read(buffer);

while (count >= 0) {
  ...
  count = stream.read(buffer);
}

, , ,

+2
source

I do this, but it is more or less the same.

    InputStream input;
    final int bytes = 100;
    final byte[] bArray = new byte[bytes];
    input.read(bArray, 0, bytes);

    int c = input.read();
    while (c >= 0) {
       ............. 
       .............

        c = input.read();
    }
0
source

All Articles