[BUG] InputStream.readNBytes doesn't correctly check for EOF

Rob Spoor openjdk at icemanx.nl
Sun Dec 20 17:47:17 UTC 2020


According to the documentation of InputStream.readNBytes:

   Reads up to a specified number of bytes from the input stream. This
   method blocks until the requested number of bytes have been read, end
   of stream is detected, or an exception is thrown. This method does not
   close the input stream.

However, despite a comment, currently it may not necessarily read up to 
EOF. The problem is in a small result checking error:

             // read to EOF which may read more or less than buffer size
             while ((n = read(buf, nread,
                     Math.min(buf.length - nread, remaining))) > 0) {
                 nread += n;
                 remaining -= n;
             }

That "> 0" is incorrect here; it's allowed to return 0 before EOF has 
been reached. It should be ">= 0", "> -1" or "!= -1", all of which 
correctly treat 0 and only break the loop once the read operation 
returns -1. Based on what's used in transferTo the best choice is 
probably ">= 0", to remain consistent in the same file.


More information about the core-libs-dev mailing list