What's the most efficient way to put as many bytes as possible from a ByteBuffer bbuf_src
into another ByteBuffer bbuf_dest
(as well as know how many bytes were transferred)? I'm trying bbuf_dest.put(bbuf_src)
but it seems to want to throw a BufferOverflowException and I can't get the javadocs from Sun right now (network problems) when I need them. >:( argh.
edit: darnit, @Richard's approach (use put() from the backing array of bbuf_src
) won't work if bbuf_src is a ReadOnly buffer, as you can't get access to that array. What can I do in that case???
To get a ByteBuffer that points to an existing byte array, you can use the wrap function: byte[] array = /* something */; ByteBuffer buffer = ByteBuffer. wrap(array);
By default, the order of a ByteBuffer object is BIG_ENDIAN. If a byte order is passed as a parameter to the order method, it modifies the byte order of the buffer and returns the buffer itself. The new byte order may be either LITTLE_ENDIAN or BIG_ENDIAN.
In order to get the byte array from ByteBuffer just call the ByteBuffer. array() method. This method will return the backed array. Now you can call the String constructor which accepts a byte array and character encoding to create String.
As the documentation of the BufferUtils in LWJGL also say: There is no way to explicitly free a ByteBuffer . The ByteBuffer objects that are allocated with the standard mechanism (namely, by directly or indirectly calling ByteBuffer#allocateDirect ) are subject to GC, and will be cleaned up eventually.
As you've discovered, getting the backing array doesn't always work (it fails for read only buffers, direct buffers, and memory mapped file buffers). The better alternative is to duplicate your source buffer and set a new limit for the amount of data you want to transfer:
int maxTransfer = Math.min(bbuf_dest.remaining(), bbuf_src.remaining());
// use a duplicated buffer so we don't disrupt the limit of the original buffer
ByteBuffer bbuf_tmp = bbuf_src.duplicate ();
bbuf_tmp.limit (bbuf_tmp.position() + maxTransfer);
bbuf_dest.put (bbuf_tmp);
// now discard the data we've copied from the original source (optional)
bbuf_src.position(bbuf_src.position() + maxTransfer);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With