我的课如下:
final ByteBuffer data;
1st_constructor(arg1, arg2, arg3){
data = ByteBuffer.allocate(8);
// Use "put" method to add values to the ByteBuffer
//.... eg: 2 ints
//....
}
1st_constructor(arg1, arg2){
data = ByteBuffer.allocate(12);
// Use "put" method to add values to the ByteBuffer
//.... eg: 3 ints
//....
}
我从此类创建了一个称为“测试”的对象:
然后,我创建了一个byte []。
byte[] buf = new byte[test.data.limit()];
但是,当我尝试将对象中的ByteBuffer复制到byte []时,出现错误。
test.data.get(buf,0,buf.length);
错误是:
Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.HeapByteBuffer.get(Unknown Source)
at mtp_sender.main(mtp_sender.java:41)
感谢您的帮助。
最佳答案
在写入缓冲区和尝试从缓冲区读取之间,请调用Buffer.flip()。这会将极限设置为当前位置,并将位置设置回零。
在执行此操作之前,限制是容量,该位置是下一个要写入的位置。如果尝试在flip()之前获取get(),它将从当前位置向前读取到限制。这是缓冲区尚未写入的部分。它具有限制-位置字节,小于您在get()中请求的限制字节-因此会抛出缓冲区下溢异常。