2

容量を変更または削減せずに、ByteBuffer から最初のnバイトを削除するにはどうすればよいですか? 結果は、0 番目のバイトがn+1バイトになるはずです。このタイプのアクションを実行するためのJavaのより良いデータ型はありますか?

4

4 に答える 4

3

次のようなことを試すことができます:

public void removeBytesFromStart(ByteBuffer bf, int n) {
    int index = 0;
    for(int i = n; i < bf.position(); i++) {
        bf.put(index++, bf.get(i));
        bf.put(i, (byte)0);
    }
    bf.position(index);
}

またはこのようなもの:

public void removeBytesFromStart2(ByteBuffer bf, int n) {
    int index = 0;
    for(int i = n; i < bf.limit(); i++) {
        bf.put(index++, bf.get(i));
        bf.put(i, (byte)0);
    }
    bf.position(bf.position()-n);
}

これは、 ByteBufferクラスの絶対getおよびputメソッドを使用して、次の書き込み位置に位置を設定します。

絶対putメソッドはオプションであることに注意してください。つまり、抽象クラスを拡張するクラスは、ByteBufferその実装を提供しない場合があります。たとえば、ReadOnlyBufferException.

位置までループするか制限までループするかは、バッファーの使用方法によって異なります。たとえば、位置を手動で設定する場合は、 loop until を使用することができますlimit。そうでない場合は、までループpositionするだけで十分で効率的です。

ここにいくつかのテストがあります:

@Test
public void removeBytesFromStart() {
    ByteBuffer bf = ByteBuffer.allocate(16);
    int expectedCapacity = bf.capacity();
    bf.put("abcdefg".getBytes());

    ByteBuffer expected = ByteBuffer.allocate(16);
    expected.put("defg".getBytes());

    removeBytesFromStart(bf, 3);

    Assert.assertEquals(expectedCapacity, bf.capacity());
    Assert.assertEquals(0, bf.compareTo(expected));
}

@Test
public void removeBytesFromStartInt() {
    ByteBuffer bf = ByteBuffer.allocate(16);
    int expectedCapacity = bf.capacity();
    bf.putInt(1);
    bf.putInt(2);
    bf.putInt(3);
    bf.putInt(4);

    ByteBuffer expected = ByteBuffer.allocate(16);
    expected.putInt(2);
    expected.putInt(3);
    expected.putInt(4);

    removeBytesFromStart2(bf, 4);

    Assert.assertEquals(expectedCapacity, bf.capacity());
    Assert.assertEquals(0, bf.compareTo(expected));
}
于 2013-08-03T14:18:55.980 に答える
1

すべての要素をバッファの先頭に移動するということですか? このような:

    int n = 4;
    //allocate a buffer of capacity 10 
    ByteBuffer b = ByteBuffer.allocate(10); 

    // add data to buffer
    for (int i = 0; i < b.limit(); i++) {
        b.put((byte) i);
    }

    // print buffer
    for (int i = 0; i < b.limit(); i++) {
        System.out.print(b.get(i) + " ");
    }

    //shift left the elements from the buffer
    //add zeros to the end
    for (int i = n; i < b.limit() + n; i++) {
        if (i < b.limit()) {
            b.put(i - n, b.get(i));
        } else {
            b.put(i - n, (byte) 0);
        }
    }
    //print buffer again
    System.out.println();
    for (int i = 0; i < b.limit(); i++) {
        System.out.print(b.get(i) + " ");
    }

n=4 の場合、次のように出力されます。

0 1 2 3 4 5 6 7 8 9 
4 5 6 7 8 9 0 0 0 0
于 2013-08-03T14:17:25.870 に答える