简体   繁体   中英

ByteBuffer.flip() Issue

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
    //....
    data.flip();
}

1st_constructor(arg1, arg2){
    data = ByteBuffer.allocate(12);  
    // Use "put" method to add values to the ByteBuffer
    //.... eg: 3 ints
    //....  
    data.flip()
}

In my main class, I create an instance of this class called "data_packet" and store the contents of the ByteBuffer "data" into a byte[].

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

Subsequently, when I use:

data_packet.data.getInt();

I get a "BufferUnderFlow Exception". However, if I flip the buffer again prior to using getInt(), it works fine.

So my question is, why am I required to flip the buffer again? Isn't it already set to read in the constructor?

Thank you.

flip is used to flip the ByteBuffer from "reading" (putting) to "writing" (getting): after a sequence of put are used to fill the ByteBuffer, flip will set the limit of the buffer to the current position and reset the position to zero. This has the effect of making a future get or write from the buffer write all of what was put into the buffer and no more.

After finishing the put, you might want to reuse the ByteBuffer to construct another data structure. To "unflip" it, call reset. This resets the limit to the capacity (making all of the buffer usable), and the position to 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM