Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copy duplicate() of Java's ByteBuffer

java.nio.ByteBuffer#duplicate() returns a new byte buffer that shares the old buffer's content. Changes to the old buffer's content will be visible in the new buffer, and vice versa. What if I want a deep copy of the byte buffer?

like image 489
Mr. Red Avatar asked Jul 29 '10 21:07

Mr. Red


People also ask

How do I copy byte buffer?

ByteBuffer duplicate() method in Java A duplicate buffer of a buffer can be created using the method duplicate() in the class java. nio. ByteBuffer. This duplicate buffer is identical to the original buffer.

What is ByteBuffer in Java?

ByteBuffer holds a sequence of integer values to be used in an I/O operation. The ByteBuffer class provides the following four categories of operations upon long buffers: Absolute and relative get method that read single bytes. Absolute and relative put methods that write single bytes.

How do I get ByteBuffer length?

After you've written to the ByteBuffer, the number of bytes you've written can be found with the position() method. If you then flip() the buffer, the number of bytes in the buffer can be found with the limit() or remaining() methods.

What does ByteBuffer wrap do?

wrap. Wraps a byte array into a buffer. The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa. The new buffer's capacity and limit will be array.


1 Answers

I think the deep copy need not involve byte[]. Try the following:

public static ByteBuffer clone(ByteBuffer original) {        ByteBuffer clone = ByteBuffer.allocate(original.capacity());        original.rewind();//copy from the beginning        clone.put(original);        original.rewind();        clone.flip();        return clone; } 
like image 84
mingfai Avatar answered Sep 25 '22 04:09

mingfai