简体   繁体   English

ByteBuffer.flip()问题

[英]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”的类的实例,并将ByteBuffer“ data”的内容存储到byte []中。

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

Subsequently, when I use: 随后,当我使用时:

data_packet.data.getInt();

I get a "BufferUnderFlow Exception". 我收到“ BufferUnderFlow异常”。 However, if I flip the buffer again prior to using getInt(), it works fine. 但是,如果在使用getInt()之前再次翻转缓冲区,它会正常工作。

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. flip用于将ByteBuffer从“读取”(放置)翻转到“ write”(获取):使用一系列put填充ByteBuffer后,flip会将缓冲区的限制设置为当前位置并重置该位置归零。 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. 完成放置后,您可能需要重用ByteBuffer来构造另一个数据结构。 To "unflip" it, call reset. 要“翻转”它,请调用reset。 This resets the limit to the capacity (making all of the buffer usable), and the position to 0. 这会将限制重置为容量(使所有缓冲区可用),并将位置重置为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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