Reputation: 16202
The java.nio.ByteBuffer
class has a ByteBuffer.array()
method, however this returns an array that is the size of the buffer's capacity, and not the used capacity. Due to this, I'm having quite a bit of issues.
I've noticed that using ByteBuffer.remaining()
gives me the amount of bytes that are currently being used by the buffer, so basically what I'm looking for is a way to get a byte[]
of ONLY the bytes being used. (ie, the bytes that are being displayed in ByteBuffer.remaining()
.
I've tried a few different things, but I seem to be failing, the only workaround I can think of it to create another ByteBuffer
with the allocated size of the remaining buffer, then write (x) bytes to it.
Upvotes: 4
Views: 4057
Reputation: 12022
From reading the Javadocs, I think remaining only gives you number of bytes between current position and limit.
remaining()
Returns the number of elements between the current position and the limit.
Furthermore:
A buffer's capacity is the number of elements it contains. The capacity of a buffer is never negative and never changes.
A buffer's limit is the index of the first element that should not be read or written. A buffer's limit is never negative and is never greater than its capacity.
A buffer's position is the index of the next element to be read or written. A buffer's position is never negative and is never greater than its limit.
So with all that in mind how about this:
static byte[] getByteArray(ByteBuffer bb) {
byte[] ba = new byte[bb.limit()];
bb.get(ba);
return ba;
}
This uses ByteBuffer's get(byte[] dst)
method
public ByteBuffer get(byte[] dst)
Relative bulk get method. This method transfers bytes from this buffer into the given destination array. An invocation of this method of the form src.get(a) behaves in exactly the same way as the invocation
src.get(a, 0, a.length)
Upvotes: 5
Reputation: 718986
Allocate a byte[]
if necessary, and then use the ByteBuffer.get(byte[])
or ByteBuffer.get(byte[], int, int)
method to copy bytes into the array. Depending on the state of the ByteBuffer
you may need to flip
it first.
In some cases it may also be possible to get the backing array for the ByteBuffer
, but this is not recommended ...
For more details, the javadocs are here.
Upvotes: 0