【NIO】(1) — Buffer

本文详细介绍了Java NIO中的Buffer,包括源码翻译、重要属性如capacity、limit、position和mark,以及关键方法如mark、reset、clear、flip、rewind等。还通过示例演示了缓冲区的分类,如只读缓冲区、直接缓冲区和非直接缓冲区的特性,并提及了内存映射文件I/O的概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

源码翻译

重要属性

重要方法

实操 demo


  • 源码翻译

package java.nio;

import jdk.internal.HotSpotIntrinsicCandidate;
import jdk.internal.access.JavaNioAccess;
import jdk.internal.access.SharedSecrets;
import jdk.internal.misc.Unsafe;

import java.util.Spliterator;

/**
 * 一个特定基础类型的数据容器。
 * A container for data of a specific primitive type.
 *     缓冲区是特定元素的线性有限序列。
 * <p> A buffer is a linear, finite sequence of elements of a specific
                    除了其内容之外,缓冲区的基本属性是其容量、限制和位置。
 * primitive type.  Aside from its content, the essential properties of a
 * buffer are its capacity, limit, and position: </p>
 *
 * <blockquote>
 *        缓冲区的容量是它包含的元素数。这个缓冲区的容量永远不会是负数,也不会改变。
 *   <p> A buffer's <i>capacity</i> is the number of elements it contains.  The
 *   capacity of a buffer is never negative and never changes.  </p>
 *
 *        缓冲区的限制是第一个不应该读或写的元素的索引。缓冲区的限制从不为负,也从不大于其 capacity
 *   <p> A buffer's <i>limit</i> is the index of the first element that should
 *   not be read or written.  A buffer's limit is never negative and is never
 *   greater than its capacity.  </p>
 *
 *        缓冲区的位置是要读取或写入的下一个元素的索引。缓冲区的位置从不为负,也不大于其 limit
 *   <p> A buffer's <i>position</i> is the index of the next element to be
 *   read or written.  A buffer's position is never negative and is never
 *   greater than its limit.  </p>
 *
 * </blockquote>
 *        对于每个非布尔基元类型,该类有一个子类。
 * <p> There is one subclass of this class for each non-boolean primitive type.
 *
 *
 * <h2> Transferring data </h2>
 *                                                种类
 * <p> Each subclass of this class defines two categories of <i>get</i> and
 * <i>put</i> operations: </p>
 *
 * <blockquote>
 *          相对操作从开始读取或写入一个或多个元素,从当前位置开始,然后按传输的元素数增加位置
 *   <p> <i>Relative</i> operations read or write one or more elements starting
 *   at the current position and then increment the position by the number of
 *                            如果请求的传输超过了限制,
 *   elements transferred.  If the requested transfer exceeds the limit then a
 *                get 会抛出 BufferUnderflowException
 *   relative <i>get</i> operation throws a {@link BufferUnderflowException}
 *                     put 会抛出 BufferOverflowException
 *   and a relative <i>put</i> operation throws a {@link
 *                                无论哪种情况,都不会传输数据。
 *   BufferOverflowException}; in either case, no data is transferred.  </p>
 *
 *            绝对操作采用显式元素索引,不影响位置。
 *   <p> <i>Absolute</i> operations take an explicit element index and do not
 *   affect the position.  Absolute <i>get</i> and <i>put</i> operations throw
 *   an {@link IndexOutOfBoundsException} if the index argument exceeds the
 *   limit.  </p>
 *
 * </blockquote>
 *
 *    当然,数据也可以通过一个合适的通道的I/O操作传入或传出缓冲区,该通道始终与当前位置相关。
 * <p> Data may also, of course, be transferred in to or out of a buffer by the
 * I/O operations of an appropriate channel, which are always relative to the
 * current position.
 *
 *        标记和重置
 * <h2> Marking and resetting </h2>
 *     缓冲区的标记是当调用 #reset 方法时,将重置其位置的索引。
 * <p> A buffer's <i>mark</i> is the index to which its position will be reset
 * when the {@link #reset reset} method is invoked.  The mark is not always
 *    标记并不总是被定义的,但是当它被定义时,它从不为负数,也不大于位置。
 * defined, but when it is defined it is never negative and is never greater
 *                        如果定义了标记,则当位置或限值调整为小于标记的值时,该标记将被丢弃。
 * than the position.  If the mark is defined then it is discarded when the
 * position or the limit is adjusted to a value smaller than the mark.  If the
 * 如果未定义标记,则调用 #reset 方法会引发@linkInvalidMarkException。
 * mark is not defined then invoking the {@link #reset reset} method causes an
 * {@link InvalidMarkException} to be thrown.
 *
 *        不变量
 * <h2> Invariants </h2>
 *    以下不变量用于标记、位置、限制和容量值
 * <p> The following invariant holds for the mark, position, limit, and
 * capacity values:
 *
 * <blockquote>
 *     {@code 0} {@code <=}
 *     <i>mark</i> {@code <=}
 *     <i>position</i> {@code <=}
 *     <i>limit</i> {@code <=}
 *     <i>capacity</i>
 * </blockquote>
 *
 *    新创建的缓冲区始终具有零的位置和未定义的标记。
 * <p> A newly-created buffer always has a position of zero and a mark that is
 *             初始限制可以是零,也可以是其他一些值,这取决于缓冲区的类型和构造方式。
 * undefined.  The initial limit may be zero, or it may be some other value
 * that depends upon the type of the buffer and the manner in which it is
 *                新分配的缓冲区的每个元素都初始化为零。
 * constructed.  Each element of a newly-allocated buffer is initialized
 * to zero.
 *
 *        附加操作
 * <h2> Additional operations </h2>
 *    除了访问位置、限制和容量值以及标记和重置的方法外,此类还定义了对缓冲区的以下操作
 * <p> In addition to methods for accessing the position, limit, and capacity
 * values and for marking and resetting, this class also defines the following
 * operations upon buffers:
 *
 * <ul>
 *            使缓冲区为新的通道读取或相对放置操作序列做好准备:
 *   <li><p> {@link #clear} makes a buffer ready for a new sequence of
 *   channel-read or relative <i>put</i> operations: It sets the limit to the
 *    它将设置 limit=capacity ,position=0 .
 *   capacity and the position to zero.  </p></li>
 *
 *           使缓冲区为新的通道写入或相对获取操作序列做好准备
 *   <li><p> {@link #flip} makes a buffer ready for a new sequence of
 *   channel-write or relative <i>get</i> operations: It sets the limit to the
 *    他将设置 limit=position ,position=0 .
 *   current position and then sets the position to zero.  </p></li>
 *
 *                            使缓冲区准备好重新读取它已经包含的数据:
 *   <li><p> {@link #rewind} makes a buffer ready for re-reading the data that
 *                        它保持 limit 不变,position=0 .
 *   it already contains: It leaves the limit unchanged and sets the position
 *   to zero.  </p></li>
 *
 *                          创建缓冲区的子序列:limit 和 position 都不变 .
 *   <li><p> {@link #slice} creates a subsequence of a buffer: It leaves the
 *   limit and the position unchanged. </p></li>
 *
 *                              创建缓冲区的浅副本:limit 和 position 都不变 .
 *   <li><p> {@link #duplicate} creates a shallow copy of a buffer: It leaves
 *   the limit and the position unchanged. </p></li>
 *
 * </ul>
 *
 *        只读缓冲区
 * <h2> Read-only buffers </h2>
 *    每个缓冲区都是可读的,但不是每个缓冲区都是可写的。
 * <p> Every buffer is readable, but not every buffer is writable.  The
 * 每个缓冲区类的突变方法被指定为可选操作,
 * mutation methods of each buffer class are specified as <I>optional
 *                当对只读缓冲区调用时,这些操作将引发@LinkReadOnlyBufferException。
 * operations</i> that will throw a {@link ReadOnlyBufferException} when
 * invoked upon a read-only buffer.  A read-only buffer does not allow its
 * 只读缓冲区不允许更改其内容,但其标记、位置和限制值是可变的
 * content to be changed, but its mark, position, and limit values are mutable.
 * 缓冲区是否为只读可以通过调用其 #isreadonly 方法来确定。
 * Whether or not a buffer is read-only may be determined by invoking its
 * {@link #isReadOnly isReadOnly} method.
 *
 *      线程安全
 * <h2> Thread safety </h2>
 *    多个并发线程使用缓冲区是不安全的
 * <p> Buffers are not safe for use by multiple concurrent threads.  If a
 * 缓冲区将由多个线程使用,然后应通过适当的同步控制对缓冲区的访问。
 * buffer is to be used by more than one thread then access to the buffer
 * should be controlled by appropriate synchronization.
 *
 *        调用连接
 * <h2> Invocation chaining </h2>
 *    此类中没有要返回的值的方法被指定为返回调用它们的缓冲区。
 * <p> Methods in this class that do not otherwise have a value to return are
 * specified to return the buffer upon which they are invoked.  This allows
 * 这允许将方法调用链接起来;例如,语句序列
 * method invocations to be chained; for example, the sequence of statements
 *
 * <blockquote><pre>
 * b.flip();
 * b.position(23);
 * b.limit(42);</pre></blockquote>
 *
 * can be replaced by the single, more compact statement
 *
 * <blockquote><pre>
 * b.flip().position(23).limit(42);</pre></blockquote>
 *
 *
 * @author Mark Reinhold
 * @author JSR-51 Expert Group
 * @since 1.4
 */

public abstract class Buffer {
    // 缓存的不安全访问对象
    // Cached unsafe-access object
    static final Unsafe UNSAFE = Unsafe.getUnsafe();

    /**
     * 在缓冲区中移动和拆分元素的拆分器的特性
     * The characteristics of Spliterators that traverse and split elements
     * maintained in Buffers.
     */
    static final int SPLITERATOR_CHARACTERISTICS =
        Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED;

    // Invariants: mark <= position <= limit <= capacity
    private int mark = -1;
    private int position = 0;
    private int limit;
    private int capacity;

    // Used by heap byte buffers or direct buffers with Unsafe access
    // For heap byte buffers this field will be the address relative to the
    // array base address and offset into that array. The address might
    // not align on a word boundary for slices, nor align at a long word
    // (8 byte) boundary for byte[] allocations on 32-bit systems.
    // For direct buffers it is the start address of the memory region. The
    // address might not align on a word boundary for slices, nor when created
    // using JNI, see NewDirectByteBuffer(void*, long).
    // Should ideally be declared final
    // NOTE: hoisted here for speed in JNI GetDirectBufferAddress
    long address;

    // Creates a new buffer with the given mark, position, limit, and capacity,
    // after checking invariants.
    //
    Buffer(int mark, int pos, int lim, int cap) {       // package-private
        if (cap < 0)
            throw createCapacityException(cap);
        this.capacity = cap;
        limit(lim);
        position(pos);
        if (mark >= 0) {
            if (mark > pos)
                throw new IllegalArgumentException("mark > position: ("
                                                   + mark + " > " + pos + ")");
            this.mark = mark;
        }
    }

    /**
     * Returns an {@code IllegalArgumentException} indicating that the source
     * and target are the same {@code Buffer}.  Intended for use in
     * {@code put(src)} when the parameter is the {@code Buffer} on which the
     * method is being invoked.
     *
     * @return  IllegalArgumentException
     *          With a message indicating equal source and target buffers
     */
    static IllegalArgumentException createSameBufferException() {
        return new IllegalArgumentException("The source buffer is this buffer");
    }

    /**
     * Verify that the capacity is nonnegative.
     *
     * @param  capacity
     *         The new buffer's capacity, in $type$s
     *
     * @throws  IllegalArgumentException
     *          If the {@code capacity} is a negative integer
     */
    static IllegalArgumentException createCapacityException(int capacity) {
        assert capacity < 0 : "capacity expected to be negative";
        return new IllegalArgumentException("capacity < 0: ("
            + capacity + " < 0)");
    }

    /**
     * Returns this buffer's capacity.
     *
     * @return  The capacity of this buffer
     */
    public final int capacity() {
        return capacity;
    }

    /**
     * Returns this buffer's position.
     *
     * @return  The position of this buffer
     */
    public final int position() {
        return position;
    }

    /**
     * Sets this buffer's position.  If the mark is defined and larger than the
     * new position then it is discarded.
     *
     * @param  newPosition
     *         The new position value; must be non-negative
     *         and no larger than the current limit
     *
     * @return  This buffer
     *
     * @throws  IllegalArgumentException
     *          If the preconditions on {@code newPosition} do not hold
     */
    public Buffer position(int newPosition) {
        if (newPosition > limit | newPosition < 0)
            throw createPositionException(newPosition);
        position = newPosition;
        if (mark > position) mark = -1;
        return this;
    }

    /**
     * Verify that {@code 0 < newPosition <= limit}
     *
     * @param newPosition
     *        The new position value
     *
     * @throws IllegalArgumentException
     *         If the specified position is out of bounds.
     */
    private IllegalArgumentException createPositionException(int newPosition) {
        String msg = null;

        if (newPosition > limit) {
            msg = "newPosition > limit: (" + newPosition + " > " + limit + ")";
        } else { // assume negative
            assert newPosition < 0 : "newPosition expected to be negative";
            msg = "newPosition < 0: (" + newPosition + " < 0)";
        }

        return new IllegalArgumentException(msg);
    }

    /**
     * Returns this buffer's limit.
     *
     * @return  The limit of this buffer
     */
    public final int limit() {
        return limit;
    }

    /**
     * Sets this buffer's limit.  If the position is larger than the new limit
     * then it is set to the new limit.  If the mark is defined and larger than
     * the new limit then it is discarded.
     *
     * @param  newLimit
     *         The new limit value; must be non-negative
     *         and no larger than this buffer's capacity
     *
     * @return  This buffer
     *
     * @throws  IllegalArgumentException
     *          If the preconditions on {@code newLimit} do not hold
     */
    public Buffer limit(int newLimit) {
        if (newLimit > capacity | newLimit < 0)
            throw createLimitException(newLimit);
        limit = newLimit;
        if (position > limit) position = limit;
        if (mark > limit) mark = -1;
        return this;
    }

    /**
     * Verify that {@code 0 < newLimit <= capacity}
     *
     * @param newLimit
     *        The new limit value
     *
     * @throws IllegalArgumentException
     *         If the specified limit is out of bounds.
     */
    private IllegalArgumentException createLimitException(int newLimit) {
        String msg = null;

        if (newLimit > capacity) {
            msg = "newLimit > capacity: (" + newLimit + " > " + capacity + ")";
        } else { // assume negative
            assert newLimit < 0 : "newLimit expected to be negative";
            msg = "newLimit < 0: (" + newLimit + " < 0)";
        }

        return new IllegalArgumentException(msg);
    }

    /**
     * Sets this buffer's mark at its position.
     *
     * @return  This buffer
     */
    public Buffer mark() {
        mark = position;
        return this;
    }

    /**
     * Resets this buffer's position to the previously-marked position.
     *
     * <p> Invoking this method neither changes nor discards the mark's
     * value. </p>
     *
     * @return  This buffer
     *
     * @throws  InvalidMarkException
     *          If the mark has not been set
     */
    public Buffer reset() {
        int m = mark;
        if (m < 0)
            throw new InvalidMarkException();
        position = m;
        return this;
    }

    /**
     * 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 Buffer clear() {
        position = 0;
        limit = capacity;
        mark = -1;
        return this;
    }

    /**
     * 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> After a sequence of channel-read or <i>put</i> operations, invoke
     * this method to prepare for a sequence of channel-write or relative
     * <i>get</i> operations.  For example:
     *
     * <blockquote><pre>
     * buf.put(magic);    // Prepend header
     * in.read(buf);      // Read data into rest of buffer
     * buf.flip();        // Flip buffer
     * out.write(buf);    // Write header + data to channel</pre></blockquote>
     *
     * <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 Buffer flip() {
        limit = position;
        position = 0;
        mark = -1;
        return this;
    }

    /**
     * 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 Buffer rewind() {
        position = 0;
        mark = -1;
        return this;
    }

    /**
     * Returns the number of elements between the current position and the
     * limit.
     *
     * @return  The number of elements remaining in this buffer
     */
    public final int remaining() {
        return limit - position;
    }

    /**
     * Tells whether there are any elements between the current position and
     * the limit.
     *
     * @return  {@code true} if, and only if, there is at least one element
     *          remaining in this buffer
     */
    public final boolean hasRemaining() {
        return position < limit;
    }

    /**
     * Tells whether or not this buffer is read-only.
     *
     * @return  {@code true} if, and only if, this buffer is read-only
     */
    public abstract boolean isReadOnly();

    /**
     * Tells whether or not this buffer is backed by an accessible
     * array.
     *
     * <p> If this method returns {@code true} then the {@link #array() array}
     * and {@link #arrayOffset() arrayOffset} methods may safely be invoked.
     * </p>
     *
     * @return  {@code true} if, and only if, this buffer
     *          is backed by an array and is not read-only
     *
     * @since 1.6
     */
    public abstract boolean hasArray();

    /**
     * Returns the array that backs this
     * buffer&nbsp;&nbsp;<i>(optional operation)</i>.
     *
     * <p> This method is intended to allow array-backed buffers to be
     * passed to native code more efficiently. Concrete subclasses
     * provide more strongly-typed return values for this method.
     *
     * <p> Modifications to this buffer's content will cause the returned
     * array's content to be modified, and vice versa.
     *
     * <p> Invoke the {@link #hasArray hasArray} method before invoking this
     * method in order to ensure that this buffer has an accessible backing
     * array.  </p>
     *
     * @return  The array that backs this buffer
     *
     * @throws  ReadOnlyBufferException
     *          If this buffer is backed by an array but is read-only
     *
     * @throws  UnsupportedOperationException
     *          If this buffer is not backed by an accessible array
     *
     * @since 1.6
     */
    public abstract Object array();

    /**
     * Returns the offset within this buffer's backing array of the first
     * element of the buffer&nbsp;&nbsp;<i>(optional operation)</i>.
     *
     * <p> If this buffer is backed by an array then buffer position <i>p</i>
     * corresponds to array index <i>p</i>&nbsp;+&nbsp;{@code arrayOffset()}.
     *
     * <p> Invoke the {@link #hasArray hasArray} method before invoking this
     * method in order to ensure that this buffer has an accessible backing
     * array.  </p>
     *
     * @return  The offset within this buffer's array
     *          of the first element of the buffer
     *
     * @throws  ReadOnlyBufferException
     *          If this buffer is backed by an array but is read-only
     *
     * @throws  UnsupportedOperationException
     *          If this buffer is not backed by an accessible array
     *
     * @since 1.6
     */
    public abstract int arrayOffset();

    /**
     * Tells whether or not this buffer is
     * <a href="ByteBuffer.html#direct"><i>direct</i></a>.
     *
     * @return  {@code true} if, and only if, this buffer is direct
     *
     * @since 1.6
     */
    public abstract boolean isDirect();

    /**
     * Creates a new buffer whose content is a shared subsequence of
     * this buffer's content.
     *
     * <p> The content of the new buffer will start at this buffer's current
     * position.  Changes to this buffer's content will be visible in the new
     * buffer, and vice versa; the two buffers' position, limit, and mark
     * values will be independent.
     *
     * <p> The new buffer's position will be zero, its capacity and its limit
     * will be the number of elements remaining in this buffer, its mark will be
     * undefined. The new buffer will be direct if, and only if, this buffer is
     * direct, and it will be read-only if, and only if, this buffer is
     * read-only.  </p>
     *
     * @return  The new buffer
     *
     * @since 9
     */
    public abstract Buffer slice();

    /**
     * Creates a new buffer that shares this buffer's content.
     *
     * <p> The content of the new buffer will be that of this buffer.  Changes
     * to this buffer's content will be visible in the new buffer, and vice
     * versa; the two buffers' position, limit, and mark values will be
     * independent.
     *
     * <p> The new buffer's capacity, limit, position and mark values will be
     * identical to those of this buffer. The new buffer will be direct if, and
     * only if, this buffer is direct, and it will be read-only if, and only if,
     * this buffer is read-only.  </p>
     *
     * @return  The new buffer
     *
     * @since 9
     */
    public abstract Buffer duplicate();


    // -- Package-private methods for bounds checking, etc. --

    /**
     *
     * @return the base reference, paired with the address
     * field, which in combination can be used for unsafe access into a heap
     * buffer or direct byte buffer (and views of).
     */
    abstract Object base();

    /**
     * Checks the current position against the limit, throwing a {@link
     * BufferUnderflowException} if it is not smaller than the limit, and then
     * increments the position.
     *
     * @return  The current position value, before it is incremented
     */
    final int nextGetIndex() {                          // package-private
        if (position >= limit)
            throw new BufferUnderflowException();
        return position++;
    }

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

    /**
     * Checks the current position against the limit, throwing a {@link
     * BufferOverflowException} if it is not smaller than the limit, and then
     * increments the position.
     *
     * @return  The current position value, before it is incremented
     */
    final int nextPutIndex() {                          // package-private
        if (position >= limit)
            throw new BufferOverflowException();
        return position++;
    }

    final int nextPutIndex(int nb) {                    // package-private
        if (limit - position < nb)
            throw new BufferOverflowException();
        int p = position;
        position += nb;
        return p;
    }

    /**
     * Checks the given index against the limit, throwing an {@link
     * IndexOutOfBoundsException} if it is not smaller than the limit
     * or is smaller than zero.
     */
    @HotSpotIntrinsicCandidate
    final int checkIndex(int i) {                       // package-private
        if ((i < 0) || (i >= limit))
            throw new IndexOutOfBoundsException();
        return i;
    }

    final int checkIndex(int i, int nb) {               // package-private
        if ((i < 0) || (nb > limit - i))
            throw new IndexOutOfBoundsException();
        return i;
    }

    final int markValue() {                             // package-private
        return mark;
    }

    final void discardMark() {                          // package-private
        mark = -1;
    }

    static void checkBounds(int off, int len, int size) { // package-private
        if ((off | len | (off + len) | (size - (off + len))) < 0)
            throw new IndexOutOfBoundsException();
    }

    static {
        // setup access to this package in SharedSecrets
        SharedSecrets.setJavaNioAccess(
            new JavaNioAccess() {
                @Override
                public JavaNioAccess.BufferPool getDirectBufferPool() {
                    return Bits.BUFFER_POOL;
                }
            });
    }

}
  • 重要属性


  • capacity

容量:缓冲区包含的元素数。永远不会是负数,也不会改变。

  • limit

限制:缓冲区的第一个不应该读或写的元素的索引。从不为负,也从不大于其 capacity。

  • position

位置:要读取或写入的下一个元素的索引。从不为负,也不大于其 limit。

  • mark

标记

  • 大小关系

mark <= position <= limit <= capacity 

  • 重要方法


  • #mark

将此缓冲区的标记设置在当前位置

    /**
     * Sets this buffer's mark at its position.
     */
    public final Buffer mark() {
        mark = position;
        return this;
    }
  • #reset

重置缓冲区的 position 到 mark 位置。配合 #mark 使用,如果没有 mark 值,则会抛出 InvalidMarkException 异常

    public final Buffer reset() {
        int m = mark;
        if (m < 0)
            throw new InvalidMarkException();
        position = m;
        return this;
    }
  • #clear

 为新的「通道读取或 put 」做好准备:它将设置 limit=capacity ,position=0 。

    /**
     * buf.clear();     // Prepare buffer for reading
     * in.read(buf);    // Read data
     */
    public final Buffer clear() {
        position = 0;
        limit = capacity;
        mark = -1;
        return this;
    }
  • #flip

在一系列「通道读取或 put」之后,调用此方法为「通道写入或 get」做准备。设置:limit=position ,position=0 。

      /**
     * For example:
     *
     * buf.put(magic);    // Prepend header
     * in.read(buf);      // Read data into rest of buffer
     * buf.flip();        // Flip buffer
     * out.write(buf);    // Write header + data to channel
     */
    public final Buffer flip() {
        limit = position;
        position = 0;
        mark = -1;
        return this;
    }
  • #rewind

倒带缓冲区,准备好重新读取它已经包含的数据:它保持 limit 不变,position=0。

    /**
     * out.write(buf);    // Write remaining data
     * buf.rewind();      // Rewind buffer
     * buf.get(array);    // Copy data into array
     */
    public final Buffer rewind() {
        position = 0;
        mark = -1;
        return this;
    }
  •  #remaining

返回此缓冲区中剩余的元素数,常在 while(buffer.remaining>0) 中使用。

    /**
     * Returns the number of elements between the current position and the
     * limit.
     *
     * @return  The number of elements remaining in this buffer
     */
    public final int remaining() {
        return limit - position;
    }
  •  #hasRemaining

判断缓冲区是否还有元素,确切的说是在 position 和 limit 之间是否还存在元素。

    /**
     * Tells whether there are any elements between the current position and
     * the limit.
     *
     * @return  <tt>true</tt> if, and only if, there is at least one element
     *          remaining in this buffer
     */
    public final boolean hasRemaining() {
        return position < limit;
    }
  • #slice

创建缓冲区的子序列:limit 和 position 都不变 。

  • #duplicate

创建缓冲区的浅副本:limit 和 position 都不变。

  • 实操 demo

package com.zqr.study.nio;

import java.io.FileInputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Description:
 * @Auther: zqr
 * @Date: 2019-08-15 16:29
 */
public class BufferDemo {
    public static void main(String args[]) throws Exception {
        //这用用的是文件 IO 处理
        FileInputStream fin = new FileInputStream("/Users/**/test.txt");
        //创建文件的操作管道
        FileChannel fc = fin.getChannel();
        //分配一个 10 个大小缓冲区,就是分配一个 10 个大小的 byte 数组
        ByteBuffer buffer = ByteBuffer.allocate(10);
        output("初始化", buffer);
    // 写入buffer
        fc.read(buffer);
        output("调用 read()", buffer);
    // 写模式转为读模式
        buffer.flip();
        output("调用 flip()", buffer);
    // 判断有没有可读数据
        while (buffer.remaining() > 0) {
    // 读取数据
            byte b = buffer.get();
            //System.out.println(((char)b));
        }
        output("调用 get()", buffer);
    // 归位
        buffer.clear();
        output("调用 clear()", buffer);
    // 最后把管道关闭
        fin.close();
    }

    //把这个缓冲里面实时状态给答应出来
    public static void output(String step, Buffer buffer) {
        System.out.println(step + " : ");
        //容量,数组大小
        System.out.print("capacity: " + buffer.capacity() + ", ");
        //当前操作数据所在的位置,也可以叫做游标
        System.out.print("position: " + buffer.position() + ", ");
        //锁定值,flip,数据操作范围索引只能在 position - limit 之间
        System.out.println("limit: " + buffer.limit());
    }


}

 

  • 关于缓冲区分类


  • 【Read-only buffers】只读缓冲区

每个缓冲区都是可读的,但不是每个缓冲区都是可写的。 当对只读缓冲区进行操作时,会引发 LinkReadOnlyBufferException 异常。只读缓冲区不允许更改其内容,但其标记、位置和限制值是可变的。

 #isreadonly 方法:确定是否是只读

#asReadOnlyBuffer 方法:把 buffer 转化为只读缓冲区

pass:改变原缓冲区内容,只读缓冲区也跟着改变

package com.zqr.study.nio;
import java.nio.ByteBuffer;

public class BufferDemo {
    public static void main(String args[]) throws Exception {
        ByteBuffer buffer = ByteBuffer.allocate(10);
    // 缓冲区中的数据 0-9
        for (int i = 0; i < buffer.capacity(); ++i) {
            buffer.put((byte) i);
        }
    // 创建只读缓冲区
        ByteBuffer readonly = buffer.asReadOnlyBuffer();
    // 改变原缓冲区的内容
        for (int i = 0; i < buffer.capacity(); ++i) {
            byte b = buffer.get(i);
            b *= 10;
            buffer.put(i, b);
        }
        readonly.flip();
    // 只读缓冲区的内容也随之改变
        while (readonly.remaining() > 0) {
            System.out.println(readonly.get());
        }
    }
}
  • 【direct buffer】直接缓冲区

· 优点

  1. Java虚拟机将尽最大努力在其上直接执行本地I/O操作。也就是说,在每次调用底层操作系统的一个本机I/O操作之前(或之后),它将尝试避免将缓冲区的内容复制到(或从)中间缓冲区。
  2. 直接缓冲区的内容可能位于正常垃圾收集堆之外,节省对应用程序内存占用。

· 缺点

比非直接缓冲区具有更高的分配和释放成本

· 使用 -> #allocateDirect

建议将直接缓冲区主要分配给受基础系统本机I/O操作影响的大型长期缓冲区。一般来说,只有当直接缓冲区在程序性能上产生可测量的收益时,才最好分配直接缓冲区。

  • 【non-direct buffer】非直接缓冲区
  • 直接在 JVM 堆上进行内存的分配, 本质上是 byte[] 数组的封装.
  • 因为 Non-Direct Buffer 在 JVM 堆中, 因此当进行操作系统底层 IO 操作中时, 会将此 buffer 的内存复制到中间临时缓冲区中. 因此 Non-Direct Buffer 的效率就较低.
  • #isdirect  判断是直接缓冲区还是非直接缓冲区

 

❤️


  • MappedByteBuffer

内存映射是一种读和写文件数据的方法,它可以比常规的基于流或者基于通道的 I/O 快的多。内存映射文件 I/O 是通过使文件中的 数据出现为 内存数组的内容来完成的,这其初听起来似乎不过就是将整个文件读到内存中,但是事实上并不是这样。一般来说, 只有文件中实际读取或者写入的部分才会映射到内存中。

创建 -> FileChannel.map -> demo

package com.zqr.study.nio;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class BufferDemo {
    public static void main(String args[]) throws Exception {

        RandomAccessFile file = new RandomAccessFile("/Users/**/test.txt","rw");
        FileChannel channel = file.getChannel();
    //把缓冲区跟文件系统进行一个映射关联 
        MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0,1024);
    //只要操作缓冲区里面的内容,文件内容也会跟着改变
        map.put( 0, (byte)97 );
        map.put( 10, (byte)122 );
        channel.close();
        file.close();

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值