问题描述
好吧,我已经适应了@Richard的答案:
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;
}
解决方法
将尽可能多的字节从ByteBuffer bbuf_src
放入另一个ByteBuffer
的最有效方法是什么bbuf_dest
(以及知道传输了多少字节)?我正在尝试,bbuf_dest.put(bbuf_src)
但似乎要抛出BufferOverflowException,当我需要它们时,我现在无法从Sun获取Javadocs(网络问题)。>
:( argh。
编辑:darnit,bbuf_src
如果bbuf_src是ReadOnly缓冲区,则@Richard
的方法(使用来自backing数组的put())将不起作用,因为您无法访问该数组。在那种情况下我该怎么办?