Bug in Channels.newChannel() ?

Rémi Forax forax at univ-mlv.fr
Sun Mar 27 06:12:32 PDT 2011


On 03/27/2011 03:07 PM, Alan Bateman wrote:
> Rémi Forax wrote:
>> This snippet prints 2 and 0
>>
>>     ByteArrayInputStream input = new ByteArrayInputStream(new byte[] 
>> {1, 2});
>>     ReadableByteChannel channel = Channels.newChannel(input);
>>
>>     ByteBuffer buffer = ByteBuffer.allocate(2);
>>     System.out.println(channel.read(buffer));
>>     System.out.println(channel.read(buffer));
>>
>> but should prints 2 and -1 because we reach the end of the stream.
>>
>> Rémi
>>
> The second read is with a buffer that has 0 bytes remaining and so 
> there isn't any read from the underlying input stream. It would be the 
> same thing as reading from the input stream with a zero length byte 
> array.

The equivalent code using the InputStream:

     ByteArrayInputStream input2 = new ByteArrayInputStream(new byte[] 
{1, 2});
     System.out.println(input2.read(new byte[2]));
     System.out.println(input2.read(new byte[0]));

prints 2 and -1.

So even if the bytebuffer has no remaining bytes, it should call read.


>
> -Alan.

Rémi



More information about the nio-dev mailing list