users@grizzly.java.net

Re: Simple input manipulation

From: Oleksiy Stashok <Oleksiy.Stashok_at_Sun.COM>
Date: Thu, 22 May 2008 16:43:13 +0200

Hello Wayne,

On May 21, 2008, at 11:49 , Wayne Gemmell wrote:

> On Tuesday 20 May 2008 23:27:51 Jeanfrancois Arcand wrote:
>>>>> <code>
>>>>> SelectableChannel channel = ctx.getSelectionKey().channel();
>>>>> try {
>>>>>
>>>>> CharBuffer cbuf = buffer.asCharBuffer();
>>>>> while(cbuf.hasRemaining())
>>>>> System.out.print(cbuf.get());
>>>>
>>>> Does this print what you need?
>>>
>>> This prints 3 squares, 1 on each line in debug (Netbeans) and 3 on
>>> the
>>> same line in normal run time.
>>
>> This is really strange as cbuf.get() should really return a char. Can
>> you try:
>>
>> buffer.flip();
>> byte[] bytes = new byte[buffer.limit()];
>> buffer.get(bytes);
>> Systen.out.println(new String(bytes));
>>
>> What are you seeing on the console?
> This outputs the input string as expected.
>
> Interestingly enough flipping the buffer before running
> asCharBuffer(); sets
> the buffer position to 0 and the limit to 6, asCharBuffer then sets
> the
> charbuffer limit to 3 and stated in the java docs (Any idea why it
> would do
> this?) but cbuf.flip sets the limit to 0.
IMHO what you see is correct behavior, when translating ByteBuffer ->
CharBuffer using ByteBuffer.asCharBuffer().
During translation 2 bytes of source ByteBuffer become 1 char (which
is represented by 2 bytes) of the CharBuffer. That's why you see that
strange empty squares.

If you want to perform smarter ByteBuffer -> CharBuffer translation,
probably you have to use:
CharBuffer = Charset.decode(ByteBuffer);
applying correct Charset.

This should work similar way as translating byte[] -> String.

Hope this will help.

Thanks.

WBR,
Alexey.



>
>
> --
> Regards
> Wayne
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_grizzly.dev.java.net
> For additional commands, e-mail: users-help_at_grizzly.dev.java.net
>