user2268507
user2268507

Reputation:

Assign ByteBuffer to Byte[] Error

I have a class as follows:

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
    //....  
}

I created an an object from this class called "test":

I then created a byte[].

   byte[] buf = new byte[test.data.limit()];

However, when I try and copy the ByteBuffer in the object to the byte[], I get an error.

test.data.get(buf,0,buf.length);

The error is:

Exception in thread "main" java.nio.BufferUnderflowException
at java.nio.HeapByteBuffer.get(Unknown Source)
at mtp_sender.main(mtp_sender.java:41)

Thank you for your help.

Upvotes: 0

Views: 2312

Answers (1)

Andy Thomas
Andy Thomas

Reputation: 86489

In between writing to the buffer and trying to read from it, call Buffer.flip(). This sets the limit to the current position, and sets the position back to zero.

Until you do this, the limit is the capacity, and the position is the next position to be written. If you try to get() before flipping(), it will read forward from the current position to the limit. This is the portion of the buffer not yet written to. It has limit - position bytes, which is less than the limit bytes you request in get() -- so the buffer underflow exception is thrown.

Upvotes: 3

Related Questions