每个Buffer都有以下的属性:
1. capacity
这个Buffer最多能放多少数据。capacity一般在buffer被创建的时候指定。
2. limit
在Buffer上进行的读写操作都不能越过这个下标。当写数据到buffer中时,limit一般和capacity相等,当读数据时,limit代表buffer中有效数据的长度。
3. position
读/写操作的当前下标。当使用buffer的相对位置进行读/写操作时,读/写会从这个下标进行,并在操作完成后,buffer会更新下标的值。
4. mark
一个临时存放的位置下标。调用mark()会将mark设为当前的position的值,以后调用reset()会将position属性设置为mark的值。mark的值总是小于等于position的值,如果将position的值设的比mark小,当前的mark值会被抛弃掉。这些属性总是满足以下条件:
0
基本类型对应的Buffer 除了Boolean无
CharBuffer ByteBuffer DoubleBuffer ShortBuffer LongBuffer IntBuffer FloatBuffer
都是继承Buffer (不安全的)
String str = "abcd";
ByteBuffer byteBuffer = ByteBuffer.allocate(capacity);
StringBuilder st = new StringBuilder();
byte[] bytes = str.getBytes();
byteBuffer.get(bytes);
System.out.println(byteBuffer.remaining());
System.out.println(byteBuffer.position());
其中allocate //创建一个指定capacity的ByteBuffer。
public static ByteBuffer allocate(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
return new HeapByteBuffer(capacity, capacity);
}
其中allocate //创建一个指定capacity的ByteBuffer。
public static ByteBuffer allocate(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
return new HeapByteBuffer(capacity, capacity);
}
其中remaining 是获取剩余位置:
public final int remaining() {
return limit - position;
}
是否还有位置:
public final boolean hasRemaining() {
return position < limit;
}
//clear 用途:把position设为0,把limit设为capacity,一般在把数据写入Buffer前调用。不是真的删除数据
Buffer clear()
public final Buffer clear() {
position = 0; //设置为0
limit = capacity; //极限和容量相同
mark = -1; //取消标记
return this;
}
Buffer flip()用途:把limit设为当前position,把position设为0,一般在从Buffer读出数据前调用。
public final Buffer flip() { limit = position; position = 0; mark = -1; return this; }
Buffer rewind()
public final Buffer rewind() {
position = 0;
mark = -1;
return this;
}
用途:
把position设为0,limit不变,一般在把数据重写入Buffer前调用。
Buffer对象有可能是只读的,这时,任何对该对象的写操作都会触发一个ReadOnlyBufferException。
isReadOnly()方法可以用来判断一个Buffer是否只读