0

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.

  • To be more specific, I set the size of the ByteBuffer(data) to 13. I then added a byte and 3 ints to the ByteBuffer. –  May 31 '13 at 03:43

1 Answers1

3

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.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • Thank you Andy, that seems to be it! I was wondering though, is Buffer.flip() usually called in the main method or should I call it in the class right after I have inputted the byte and 3 ints? –  May 31 '13 at 03:49
  • That's a judgment call that you're best suited to make. If there won't be anything further written after the constructor, you could make a case for preparing the buffer for reading inside the constructor. – Andy Thomas May 31 '13 at 03:52