java - overview - 將字節從一個ByteBuffer傳輸到另一個ByteBuffer



java.nio.file jar (2)

你得到BufferOverflowException,因為你的bbuf_dest不夠大。

您將需要使用bbuf_dest.remaining()來查找可以從bbuf_src傳輸的最大字節數:

int maxTransfer = Math.min(bbuf_dest.remaining(), bbuf_src.remaining());
bbuf_dest.put(bbuf_src.array(), 0, maxTransfer);

https://code.i-harness.com

將ByteBuffer bbuf_src放入另一個ByteBuffer bbuf_dest (以及知道傳輸了多少字節)的盡可能多的字節的最有效方法是什麼? 我試圖bbuf_dest.put(bbuf_src)但它似乎想要拋出一個BufferOverflowException,我無法從Sun立即獲取javadoc(網絡問題),當我需要它們時。 > :()。

編輯:darnit,@ Richard的方法(從bbuf_src的後備數組中使用put())如果bbuf_src是ReadOnly緩衝區,將無法工作,因為您無法訪問該數組。 我能做什麼呢?


好的,我已經修改了理查德的回答:

public static int transferAsMuchAsPossible(
                     ByteBuffer bbuf_dest, ByteBuffer bbuf_src)
{
  int nTransfer = Math.min(bbuf_dest.remaining(), bbuf_src.remaining());
  if (nTransfer > 0)
  {
    bbuf_dest.put(bbuf_src.array(), 
                  bbuf_src.arrayOffset()+bbuf_src.position(), 
                  nTransfer);
    bbuf_src.position(bbuf_src.position()+nTransfer);
  }
  return nTransfer;
}

並進行測試以確保其正常工作:

public static boolean transferTest()
{
    ByteBuffer bb1 = ByteBuffer.allocate(256);
    ByteBuffer bb2 = ByteBuffer.allocate(50);
    for (int i = 0; i < 100; ++i)
    {
        bb1.put((byte)i);
    }
    bb1.flip();
    bb1.position(5);
    ByteBuffer bb1a = bb1.slice();
    bb1a.position(2);
    // bb3 includes the 5-100 range
    bb2.put((byte)77);
    // something to see this works when bb2 isn't empty
    int n = transferAsMuchAsPossible(bb2, bb1a);
    boolean itWorked = (n == 49);

    if (bb1a.position() != 51)
        itWorked = false;
    if (bb2.position() != 50)
        itWorked = false;
    bb2.rewind();
    if (bb2.get() != 77)
        itWorked = false;
    for (int i = 0; i < 49; ++i)
    {
        if (bb2.get() != i+7)
        {
            itWorked = false;
            break;
        }
    }
    return itWorked;
}




nio