RFR 8139206: Add InputStream readNBytes(int len)

Adam Petcher adam.petcher at oracle.com
Mon Jan 22 15:56:12 UTC 2018

The spec of the new method doesn't give me enough information to 
determine whether it is safe to call it when the value of the length 
argument is much larger than the number of bytes I expect to actually 
read. This use case comes up frequently in security libraries, because 
we have to handle length values that were chosen by an attacker. Would 
it be possible to add a sentence or two to the spec to clarify this 

Possible wording, if this method can be called with large length values:

"The total amount of memory allocated by this method is proportional to 
the number of bytes read from the stream. Therefore, the method may be 
safely called with very large values of {@code len}.

Possible wording, otherwise:

"The total amount of memory allocated by this method may be proportional 
to the value of {@code len}. Therefore, calling this method with very 
large values of {@code len} is not recommended."

On 1/17/2018 11:24 AM, Brian Burkhalter wrote:
> The proposed change has been modified to replace the two methods
> byte[] InputStream.readAllBytes(int) // reads at most ‘len’ bytes
> byte[] InputStream.readNBytes(int) // reads exactly ‘len’ bytes or throws IOException
> with a single method
> byte[] InputStream.readNBytes(int) // reads at most ‘len’ bytes
> A negative value of ‘len’ will now cause an IllegalArgumentException instead of an IndexOutOfBoundsException. Also some verbiage has been improved.
> http://cr.openjdk.java.net/~bpb/8139206/webrev.01/
> Thanks,
> Brian
> On Jan 16, 2018, at 11:17 AM, Brian Burkhalter <brian.burkhalter at oracle.com> wrote:
>> https://bugs.openjdk.java.net/browse/JDK-8139206
>> http://cr.openjdk.java.net/~bpb/8139206/webrev.00/
>> This change would add a new method “byte[] InputStream.readNBytes(int len)” which would read up to at most ‘len’ bytes from  the stream and return them in an internally allocated array.

More information about the core-libs-dev mailing list