ByteBuffer三个常见方法小结 filp(),rewind(),clear()

关于缓冲器ByteBuffer的三个方法:flip(),clear(),remind()。

[b]一、[/b]flip():反转此缓冲区,将限制设置为当前位置,然后将位置设置为 0 !

之前的写操作会不断更新当前位置,当写操作完成之后,需调用此方法,将限制位置设置为当前位置,将当前位置设置为0,这样下一个读操作会从0开始,直到限制位置。



/**
* Flips this buffer. The limit is set to the current position and then
* the position is set to zero. If the mark is defined then it is
* discarded.
*
* <p> This method is often used in conjunction with the {@link
* java.nio.ByteBuffer#compact compact} method when transferring data from
* one place to another. </p>
*
* @return This buffer
*/
public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
}



public byte get() {
return hb[ix(nextGetIndex())];
}

final int nextGetIndex() { // package-private
if (position >= limit)
throw new BufferUnderflowException();
return position++;
}


[b]二、[/b]remain():与flip不同的是,不会修改限制位置。

比如初始化时:
ByteBuffer buffer=ByteBuffer.allocate(1024);


那么做读操作的时候就会读到第(1024-1)个索引,而flip却不一定能读到(1024-1)个索引,这取决于他的写操作的数据长度。


/**
* Rewinds this buffer. The position is set to zero and the mark is
* discarded.
*
* <p> Invoke this method before a sequence of channel-write or <i>get</i>
* operations, assuming that the limit has already been set
* appropriately. For example:
*
* <blockquote><pre>
* out.write(buf); // Write remaining data
* buf.rewind(); // Rewind buffer
* buf.get(array); // Copy data into array</pre></blockquote>
*
* @return This buffer
*/
public final Buffer rewind() {
position = 0;
mark = -1;
return this;
}


[b]三、[/b]clear():“清除”此缓冲区,将位置设置为 0,将限制设置为容量!此方法不能实际清除缓冲区中的数据,但从名称来看它似乎能够这样做,这样命名是因为它多数情况下确实是在清除数据时使用。因为调用该方法后,我们一般都会调用FileChannel.read(buff)或者buff.put()来把新的数据放到buff中,此时原来的内容就会被新的内容所覆盖!也不是全部覆盖,而是覆盖掉新数据所包含的字节数!所以看起来好象就是原来的内容被删除一样!


/**
* Clears this buffer. The position is set to zero, the limit is set to
* the capacity, and the mark is discarded.
*
* <p> Invoke this method before using a sequence of channel-read or
* <i>put</i> operations to fill this buffer. For example:
*
* <blockquote><pre>
* buf.clear(); // Prepare buffer for reading
* in.read(buf); // Read data</pre></blockquote>
*
* <p> This method does not actually erase the data in the buffer, but it
* is named as if it did because it will most often be used in situations
* in which that might as well be the case. </p>
*
* @return This buffer
*/
public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
}


[b]四、[/b]ByteBuffer类中提供position(),remaining(),hasRemaining(),limit()等方法来验证以上三点。

[b]五、[/b]上述代码中提到的:

and the mark is discarded.


参照mark(),reset()方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值