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