Assign ByteBuffer to Byte[] Error



我有一个类如下:

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()。这将限制设置为当前位置,并将位置设置为零。

在您这样做之前,限制是容量,而位置是下一个要写入的位置。如果在翻转()之前尝试get(),它将从当前位置向前读取到极限。这是缓冲区中尚未写入的部分。它有limit - position字节,少于你在get()中请求的limit字节——所以会抛出缓冲区底流异常。

相关内容

最新更新