what am i doing wrong here?
i know the answer will make me feel like the idiot i am, but please help me see it:
I have a ByteBuffer. I need to create a byte array of length bytes (length < bytes allocated always).
Here's the code:position = formattedLine.position();
byte wrapped[] =newbyte[position];
formattedLine.get(wrapped,0,wrapped.length);
return wrapped;
I keep getting a BufferUnderflowException on the .get method call. However,
the formattedLine object already always contains more bytes than position.
I'm confused, please set me straight here people! Thanks
[736 byte] By [
pnandrusa] at [2007-11-27 10:51:34]

> Use remaining, not position.
wait, but i want the bytes from 0 to position, not from position to the end.
>what is formattedLine?
it is a ByteBuffer object, allocated to 2000 bytes, but usually has less than that. I
need to transfer the actual amount of bytes into a byte array with nothing trailing.
> wait, but i want the bytes from 0 to position, not
> from position to the end.
Isn't that cheating? Why do want to do that?
Method get starts reading from the current position. Perhaps calling rewind or setting the position to 0 will do what you want, whatever that is.
here's the problem, I have to allocate the ByteBuffer for a max size, but once
i've done my work with the ByteBuffer I have a certain number of bytes that are
almost always less than the allocated space.
However, i don't want any of the blank space on the end. I only want up to the last byte i appended to my ByteBuffer.
When i return ByteBuffer.array i get a byte array the size allocated. I could just
copy the array one byte at a time, but i wanted to see if there was a slicker
(possibly faster) method for doing this internally in ByteBuffer. This method will
be called a ton of times and could be a potential bottleneck so i have to keep care
of how i program this part. Just looking for suggestions.
Sorry, i probably should have specified my ends in the beginning. Let me know
if you have any more suggestions. thanks
> Method get starts reading from the current position.
> Perhaps calling rewind or setting the position to 0
> will do what you want, whatever that is.
AH-HAH! that's it i'm sure. i thought it started reading from the array offset, which
was 0.
UPDATE: that worked. Thanks guys! I'll explain my ends better next time.
thanks again for your time spent haggling!