我有一个类(class)如下:
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
//....
}
我从这个类创建了一个名为“test”的对象:
然后我创建了一个字节[]。
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() 。这会将限制设置为当前位置,并将位置设置回零。
在执行此操作之前,限制就是容量,而位置就是下一个要写入的位置。如果您尝试在 Flipping() 之前尝试 get(),它将从当前位置向前读取到限制。这是缓冲区中尚未写入的部分。它有 limit -position 个字节,小于您在 get() 中请求的 limit 个字节——因此会抛出缓冲区下溢异常。
关于java - 将 ByteBuffer 分配给 Byte[] 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16849341/