JAVA学习——Buffer

 

 

Buffer定义

Buffer 在 java.nio 包中实现,被定义成抽象类

Buffer的实现类关系:

 

创建Buffer

创建Buffer的方法(以ByteBuffer为例)主要是

allocate

    public static ByteBuffer allocate(int capacity) {
        if (capacity < 0)
            throw new IllegalArgumentException();
        //返回一个堆内Buffer
        return new HeapByteBuffer(capacity, capacity);
    }

wrap

public static ByteBuffer wrap(byte[] array,
                                    int offset, int length)
    {
        try {
            return new HeapByteBuffer(array, offset, length);
        } catch (IllegalArgumentException x) {
            throw new IndexOutOfBoundsException();
        }
    }

allocateDirect

    public static ByteBuffer allocateDirect(int capacity) {
        //返回一个堆外Buffer
        return new DirectByteBuffer(capacity);
    }

备注:关于 Direct Buffer 和 Non-Direct Buffer 的区别可以自行百度

写数据

写数据一般指的是将Channel的数据写入Buffer中,这个操作对于Buffer是写操作,对于系统是读操作(将外部数据读到系统中)

public abstract ByteBuffer put(byte b);

读数据

读数据一般指的是将 Buffer 中的数据写入到Channel 中。在系统层面上,这个操作我们称为写操作

public abstract byte get();

主要方法

rewind() :重置操作,可以重新进行读写操作

public final Buffer rewind() {
        //重置起始位置
        position = 0;
        //重置标记
        mark = -1;
        return this;
    }

 

flip() :从写模式切换到读模式

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;
    }

 

mark():保存当前操作的位置

public final Buffer mark() {
        mark = position;
        return this;
    }

 

reset():恢复mark前的位置

public final Buffer reset() {
        int m = mark;
        //没有进行mark前执行此操作会抛出异常
        if (m < 0)
            throw new InvalidMarkException();
        position = m;
        return this;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大·风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值