Java ByteBuffer copy to another ByteBuffer
import java.nio.ByteBuffer; public class Main { public static void main(String[] argv) { ByteBuffer b = ByteBuffer.wrap("demo2s.com".getBytes()); ByteBuffer c = ByteBuffer.allocate(30); copy(b, c);//from w w w. jav a 2s. co m System.out.println(b); System.out.println(c); } public final static int copy(final ByteBuffer from, final ByteBuffer to) { final int len = from.limit(); return copy(from, 0, to, 0, len); } public final static int copy(final ByteBuffer from, final int offset1, final ByteBuffer to, final int offset2, final int len) { System.arraycopy(from.array(), offset1, to.array(), offset2, len); to.limit(offset2 + len); return len; } }
import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Main { public static void main(String[] argv) { ByteBuffer b = ByteBuffer.wrap("demo2s.com".getBytes()); ByteBuffer c = copyByteBuffer(b); System.out.println(b);/*from w ww. j a v a 2s.co m*/ System.out.println(c); } public static ByteBuffer copyByteBuffer(ByteBuffer paramByteBuffer) { ByteBuffer localByteBuffer = newByteBuffer(paramByteBuffer .remaining()); paramByteBuffer.mark(); localByteBuffer.put(paramByteBuffer); paramByteBuffer.reset(); localByteBuffer.rewind(); return localByteBuffer; } public static ByteBuffer newByteBuffer(int paramInt) { ByteBuffer localByteBuffer = ByteBuffer.allocateDirect(paramInt); localByteBuffer.order(ByteOrder.nativeOrder()); return localByteBuffer; } }
import java.nio.ByteBuffer; public class Main { public static void main(String[] argv) { ByteBuffer b = ByteBuffer.wrap("demo2s.com".getBytes()); ByteBuffer c = copyByteBuffer(b); System.out.println(b);//from w w w . j a v a2s . c o m System.out.println(c); } public static java.nio.ByteBuffer copyByteBuffer(java.nio.ByteBuffer data) { if (data == null) { return null; } java.nio.ByteBuffer buf = createDirectByteBuffer(convertByteBufferToArray(data)); return buf; } public static java.nio.ByteBuffer createDirectByteBuffer(byte[] data) { if (data == null) { return null; } java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocateDirect((Byte.SIZE / 8) * data.length) .order(java.nio.ByteOrder.nativeOrder()); buf.clear(); buf.put(data); buf.flip(); return buf; } public static byte[] convertByteBufferToArray(java.nio.ByteBuffer buf) { if (buf.hasArray()) { return buf.array(); } else { buf.rewind(); byte[] array = new byte[buf.remaining()]; int index = 0; while (buf.hasRemaining()) { array[index++] = buf.get(); } return array; } } }