27

java.nio.ByteBuffer#duplicate()古いバッファの内容を共有する新しいバイト バッファを返します。古いバッファのコンテンツへの変更は新しいバッファに表示され、その逆も同様です。バイト バッファのディープ コピーが必要な場合はどうすればよいですか?

4

6 に答える 6

45

ディープコピーに を含める必要はないと思います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;
}
于 2010-11-02T00:02:34.653 に答える
22

この質問は、 をコピーする最初のヒットの 1 つとして今でも出てくるので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;
于 2014-01-27T18:00:00.583 に答える
3

mingfaiのソリューションに基づいています:

これにより、ほぼ真のディープコピーが得られます。失われるのはマークだけです。orig が HeapBuffer であり、オフセットがゼロでないか、容量がバッキング配列よりも小さい場合、範囲外のデータはコピーされません。

public static ByteBuffer deepCopy( ByteBuffer orig )
{
    int pos = orig.position(), lim = orig.limit();
    try
    {
        orig.position(0).limit(orig.capacity()); // set range to entire buffer
        ByteBuffer toReturn = deepCopyVisible(orig); // deep copy range
        toReturn.position(pos).limit(lim); // set range to original
        return toReturn;
    }
    finally // do in finally in case something goes wrong we don't bork the orig
    {
        orig.position(pos).limit(lim); // restore original
    }
}

public static ByteBuffer deepCopyVisible( ByteBuffer orig )
{
    int pos = orig.position();
    try
    {
        ByteBuffer toReturn;
        // try to maintain implementation to keep performance
        if( orig.isDirect() )
            toReturn = ByteBuffer.allocateDirect(orig.remaining());
        else
            toReturn = ByteBuffer.allocate(orig.remaining());

        toReturn.put(orig);
        toReturn.order(orig.order());

        return (ByteBuffer) toReturn.position(0);
    }
    finally
    {
        orig.position(pos);
    }
}
于 2012-11-20T03:13:59.723 に答える
1

バッファ全体を反復処理し、値ごとに新しいバッファにコピーする必要があります。

于 2010-07-29T21:05:01.387 に答える