Java Bytebuffer完全填满
我目前正在使用Java ByteBufferJava Bytebuffer完全填满,java,arrays,nio,bytebuffer,Java,Arrays,Nio,Bytebuffer,我目前正在使用Java ByteBuffer ByteBuffer batch = ByteBuffer.allocate(tuple_size * batch_size ) ; int pos = 0; int sent = 0; while ( sent++ < batch_size) { Event event = (Event) it.next(); batch.put(event.getData(),
ByteBuffer batch = ByteBuffer.allocate(tuple_size * batch_size ) ;
int pos = 0;
int sent = 0;
while ( sent++ < batch_size) {
Event event = (Event) it.next();
batch.put(event.getData(), pos, tuple_size);
pos += tuple_size;
}
return batch.array();
我得到:
0 200 0 200(第0轮)
100(第1轮)
这正是人们所期望的。现在,根据文档,绑定支票似乎确实有效:
offset - The offset within the array of the first byte to be read; must be non-negative and no larger than array.length
length - The number of bytes to be read from the given array; must be non-negative and no larger than array.length - offset
如何完全填满缓冲区?(同时保持基础缓冲区的长度为tuple\u size*batch\u size?从您的问题看,tuple\u size是否足够大,以容纳event.getData()。 如果不是,那将导致你的IndexOutofBoundsException。 也许差一点 另一种可能是迭代器
it
只包含一个元素
编辑:根据文档,如果缓冲区空间不足,您应该得到一个BufferOverflowException。
引用文件:
此方法将字节从给定源传输到此缓冲区
数组。如果要从阵列复制的字节数超过剩余字节数
在这个缓冲区中,也就是说,如果length>remaining(),则不需要任何字节
已传输,并引发BufferOverflowException
这表明您的问题不是您所期望的。我认为您不需要pos变量。
put
方法正在尝试读取位置pos处的event.getData()
,而我认为您希望从位置0读取event.getData()
。您只需使用batch.put(event.getData())
将数组的全部内容附加到缓冲区中。event.getData()始终等于tuple_size,并且默认情况下队列始终包含1024个元素。我会得到IndexArrayOutofBound异常。不是BufferOverflowException,因为checkBound方法失败。但我不知道它为什么会失败。阅读文档,这非常有意义。这不是我所期望的相对put操作的工作方式;如果您需要类似的功能,您必须首先调用position()
,然后调用put()
。完美。谢谢正如Buhb所说的,我不希望put以这种方式工作。相反,偏移量是相对于ByteBuffer的。
offset - The offset within the array of the first byte to be read; must be non-negative and no larger than array.length
length - The number of bytes to be read from the given array; must be non-negative and no larger than array.length - offset