Java-NIO之Buffer(缓冲区)

本文介绍了Java NIO中的Buffer,包括其基本构成、使用方法、功能以及在多线程和文件读取中的应用。Buffer是一个数据容器,用于与NIO Channel交互,防止内存占用过大并支持分段读写。直接缓冲区和非直接缓冲区各有优劣,前者通过物理内存分配提高性能。

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

Buffer 是什么

Buffer(缓冲区)本质上是一个由基本类型数组构成的容器。

我们先看看Buffer类的基本构成:

public abstract class Buffer {
    // Invariants: mark <= position <= limit <= capacity
    private int mark = -1;
    private int position = 0;
    private int limit;
    private int capacity;
}

再看看子类ByteBuffer 的构成:

public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer>{
    // These fields are declared here rather than in Heap-X-Buffer in order to
    // reduce the number of virtual method invocations needed to access these
    // values, which is especially costly when coding small buffers.
    //
    final byte[] hb;                  // Non-null only for heap buffers
    final int offset;
    boolean isReadOnly;
}

因此一个ByteBuffer 对象由基本的五大属性组成:

核心属性:

● mark 初始值为-1,用以标记当前position的位置。对应方法为 mark()。

● position 初始值为0,读、写数据的起点位置。对应方法为 position()。

● limit 界限,和position 组成可读、可写的数据操作区间。对应方法为 limit()。

● capacity 缓冲区的大小。对应方法为capacity()。

数据存储:

● hb 一个基本类型构成的数据,大小等于capacity。

Buffer 如何使用

核心方法:

● put() 写数据。

● get() 读数据。

● flip() 翻转。如当 put 完数据之后,调用flip s 是为了告知下次 get 数据需要读取数据区间。反过来也是一样的道理。

public final Buffer flip() {
        limit = position;
        position = 0;
        mark = -1;
        return this;
    }

● clear() 清空。不会清除数据,但会各个属性回归初始值。

public final Buffer clear() {
        position = 0;
        limit = capacity;
        mark = -1;
        return this;
    }

● rewind 倒带。当需要重读、重写的时候可以使用。

public final Buffer rewind() {
        position = 0;
        mark = -1;
        return this;
    }

● remaning() 返回剩余未被处理的数量。

public final int remaining() {
        return limit - position;
    }

假设我们声明了一个 capacity 为 5 的字节缓冲区:

ByteBuffer buf = ByteBuffer.allocate(4);

那么,缓冲区

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值