Java 的 ByteBuffer 的深度复制副本()

2022-09-01 13:41:32

java.nio.ByteBuffer#duplicate()返回共享旧缓冲区内容的新字节缓冲区。对旧缓冲区内容的更改将在新缓冲区中可见,反之亦然。如果我想要字节缓冲区的深层副本,该怎么办?


答案 1

我认为深度复制不需要涉及.请尝试以下操作:byte[]

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

答案 2

由于这个问题仍然是复制的第一个命中之一,我将提供我的解决方案。此解决方案不会触及原始缓冲区(包括任何标记集),并且将返回与原始缓冲区容量相同的深层副本。ByteBuffer

public static ByteBuffer cloneByteBuffer(final ByteBuffer original) {
    // Create clone with same capacity as original.
    final ByteBuffer clone = (original.isDirect()) ?
        ByteBuffer.allocateDirect(original.capacity()) :
        ByteBuffer.allocate(original.capacity());

    // Create a read-only copy of the original.
    // This allows reading from the original without modifying it.
    final ByteBuffer readOnlyCopy = original.asReadOnlyBuffer();

    // Flip and read from the original.
    readOnlyCopy.flip();
    clone.put(readOnlyCopy);

    return clone;
}

如果一个人关心仓位,限制或订单的设置与原始位置,那么这是对上述内容的简单补充:

clone.position(original.position());
clone.limit(original.limit());
clone.order(original.order());
return clone;

推荐