javawhile-looppmd

PMD compliant stream copy in java


I have a piece of code for stream copying.

OutputStream os = ...;
InputStream is = ...;
int bufferLength;
byte[] buffer = new byte[1024];
while ((bufferLength = is.read(buffer)) != -1) {
   os.write(buffer, 0, bufferLength);
}

If I run PMD over it, I get the following warning http://pmd.sourceforge.net/rules/controversial.html#AssignmentInOperand.

Now I wish to get rid of that warning, but the only alternative I can think of is something like

OutputStream os = ...;
InputStream is = ...;
int bufferLength;
byte[] buffer = new byte[1024];
bufferLength = is.read(buffer);
while (bufferLength != -1) {
   os.write(buffer, 0, bufferLength);
   bufferLength = is.read(buffer);
}

And I don't really like that because I end up duplicating code. Is there a more elegant way to satisfy this PMD rule?


Solution

  • I just wanted to advice you to use Commons IO:

    IOUtils.copy(is, os);
    

    and then I had a quick look at the source code of copy():

    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    int n = 0;
    while (-1 != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
    }
    

    I would assume your code is valid and leave it as-is. Or maybe do-while loop will do the trick?