---
title: "ByteBuffer三个常见方法小结 filp(),rewind(),clear()"
author: "prowl"
date: "2009-10-20T17:31:58Z"
tags: []
slug: "bytebuffer-filp-rewind-clear"
draft: false
lastmod: "2009-10-20T17:45:56Z"
id: 497106
url: "https://prowl.iteye.com/blog/497106"
---

关于缓冲器ByteBuffer的三个方法：flip(),clear(),remind()。

**一、**flip():反转此缓冲区，将限制设置为当前位置，然后将位置设置为 0 ！

之前的写操作会不断更新当前位置，当写操作完成之后，需调用此方法，将限制位置设置为当前位置，将当前位置设置为0，这样下一个读操作会从0开始，直到限制位置。



```java

   /**
     * 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;
    }

```



```java

    public byte get() {
        return hb[ix(nextgetindex())];
    }

    final int nextGetIndex() {	// package-private
        if (position >= limit)
            throw new BufferUnderflowException();
        return position++;
    }

```


**二、**remain():与flip不同的是，不会修改限制位置。

比如初始化时：

```java
ByteBuffer buffer=ByteBuffer.allocate(1024);
```


那么做读操作的时候就会读到第(1024-1)个索引，而flip却不一定能读到(1024-1)个索引，这取决于他的写操作的数据长度。


```java

    /**
     * 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;
    }

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

```java

    /**
     * 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;
    }

```


**四、**ByteBuffer类中提供position(),remaining(),hasRemaining()，limit()等方法来验证以上三点。

**五、**上述代码中提到的:


```java
and the mark is discarded.

```


参照mark(),reset()方法。