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?
views:
207answers:
5
+1
A:
You'll need to iterate the entire buffer and copy by value into the new buffer.
Kylar
2010-07-29 21:05:01
There's an (optional) overload of the `put` method that does this for you though.
nos
2010-07-29 21:08:02
Woohoo! I learned something new.
Kylar
2010-07-29 22:11:25
A:
You will have to use System.arraycopy
to duplicate the values of the buffer to the new buffer
webdestroya
2010-07-29 21:05:46
+1
A:
public static ByteBuffer copy(ByteBuffer b) {
byte[] oldBytes = b.array();
byte[] copiedBytes = new byte[oldBytes.length];
// (Object src, int srcPos, Object dest, int destPos, int length)
System.arraycopy(oldBytes, 0, copiedBytes, 0, oldBytes.length);
ByteBuffer duplicate = ByteBuffer.wrap(copiedBytes);
return duplicate;
}
should work, but haven't tested it.
I82Much
2010-07-29 21:08:50
A:
Writing your own code is an option and the answers so far should work fine. For a more generic solution there's also Serialization ( http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2 ) and there are utilities to make deep copies of things, like http://www.genericdeepcopy.com/ and http://robust-it.co.uk/clone/.
Aaron
2010-08-15 01:34:53