将字节从一个ByteBuffer传输到另一个ByteBuffer [英] transferring bytes from one ByteBuffer to another
问题描述
将ByteBuffer bbuf_src
中尽可能多的字节放入另一个ByteBuffer bbuf_dest
的最有效方法是什么?以及知道传输了多少字节)?我正在尝试 bbuf_dest.put(bbuf_src)
但似乎想要抛出一个BufferOverflowException,我现在无法从Sun获取javadoc(网络问题)需要它们。 > :( argh。
What's the most efficient way to put as many bytes as possible from a ByteBuffer bbuf_src
into another ByteBuffer bbuf_dest
(as well as know how many bytes were transferred)? I'm trying bbuf_dest.put(bbuf_src)
but it seems to want to throw a BufferOverflowException and I can't get the javadocs from Sun right now (network problems) when I need them. >:( argh.
编辑:darnit,@ Richard的方法(使用来自<$的支持数组的put()如果bbuf_src是一个ReadOnly缓冲区,则c $ c> bbuf_src )将无效。因为你无法访问该数组。在这种情况下我该怎么办???
edit: darnit, @Richard's approach (use put() from the backing array of bbuf_src
) won't work if bbuf_src is a ReadOnly buffer, as you can't get access to that array. What can I do in that case???
推荐答案
好的,我改编了@ Richard的回答:
OK, I've adapted @Richard's answer:
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;
}
以及确保其有效的测试:
and a test to make sure it works:
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传输到另一个ByteBuffer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!