初始化实例
//单位大小是byte
ByteBuffer buffer = ByteBuffer.allocate(10240);
System.out.println("buffer = " + buffer);
reset方法演示
//clear -> limit=capacity position=0 mark=-1
buffer.clear();
buffer.position(5);
//mark 标记位置 mark=position
buffer.mark();
buffer.position(10);
System.out.println("before reset:" + buffer);
//mark=-1抛异常 else position=mark
buffer.reset();
System.out.println("after reset:" + buffer);
仅仅把position设置成之前mark的位置
rewind方法演示
buffer.clear();
buffer.position(10);
buffer.limit(15);
System.out.println("before rewind:" + buffer);
//position= 0 mark=-1
buffer.rewind();
System.out.println("after rewind:" + buffer);
读写位置置0,标识位mark=-1
compact方法演示 , 本质上就是把已读的数据丢弃
flip是写到读的切换操作
buffer.clear();
buffer.put("abcd".getBytes());
System.out.println("before compact:" + buffer);
System.out.println(new String(buffer.array()));
//写读切换 limit = position position = 0 mark = -1
//本质上就是指定了可以读取的上限 并且把游标设置到0这个位置
buffer.flip();
System.out.println("after flip:" + buffer);
System.out.println((char) buffer.get());
System.out.println((char) buffer.get());
System.out.println((char) buffer.get());
System.out.println("after three gets:" + buffer);
System.out.println("\t" + new String(buffer.array()));
buffer.compact();
System.out.println("after compact:" + buffer);
System.out.println("\t" + new String(buffer.array()));
本质上是丢弃已读内容,position直接跳到最新的可以写的位置
把从position到limit中的内容移到0到limit-position的区域内,position和limit的取值也分别变成limit-position、capacity。如果先将positon设置到limit,再compact,那么相当于clear()
compact源码部分
//把未读取的数据 向左移动,丢弃已读取过的数据
System.arraycopy(hb, ix(position()), hb, ix(0), remaining());
//position=limit-position
position(remaining());
//limit=capacity
limit(capacity());
//remark=-1
discardMark();
get方法注意
//get() 会改变position
public byte get() {
return hb[ix(nextGetIndex())];
}
final int nextGetIndex() {
if (position >= limit)
throw new BufferUnderflowException();
return position++;
}
//get(index)不会改变position
public byte get(int i) {
return hb[ix(checkIndex(i))];
}
final int checkIndex(int i) { // package-private
if ((i < 0) || (i >= limit))
throw new IndexOutOfBoundsException();
return i;
}
//会改变position 且 是从position+offset的位置开始读取内容
public ByteBuffer get(byte[] dst, int offset, int length) {
checkBounds(offset, length, dst.length);
if (length > remaining())
throw new BufferUnderflowException();
System.arraycopy(hb, ix(position()), dst, offset, length);
position(position() + length);
return this;
}
put方法
ByteBuffer bb = ByteBuffer.allocate(32);
System.out.println("before put(byte):" + bb);
System.out.println("after put(byte):" + bb.put((byte) 'a'));
System.out.println( bb.put(1, (byte) 'b'));
System.out.println( bb.put(2, (byte) 'c'));
//此时上面输出值是abc,这个会把A替代成b 因为索引此时在index=1这个位置
System.out.println( bb.put((byte) 'A'));
System.out.println( bb.put(1, (byte) 'b'));
put指定index也不会改变position的位置