Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

transferring bytes from one ByteBuffer to another

Tags:

java

javadoc

nio

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???

like image 564
Jason S Avatar asked Feb 20 '09 16:02

Jason S


People also ask

How do you convert bytes to ByteBuffer?

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);

What is the byte order of ByteBuffer?

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.

How do I get data from ByteBuffer?

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.

How can I get free ByteBuffer?

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.


1 Answers

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);
like image 115
Jules Avatar answered Sep 19 '22 00:09

Jules