netty学习之一:java.nio.ByteBuffer


public class App {
	public static void main(String[] args) {
		ByteBuffer buffer = ByteBuffer.allocate(88);
		String value = "权威指南";
		buffer.put(value.getBytes());
		System.out.println(buffer.capacity());
		System.out.println(buffer.position());
		System.out.println(buffer.limit());
		System.out.println("===================");
		buffer.flip();
		int remaining = buffer.remaining();
		System.out.println(buffer.capacity());
		System.out.println(buffer.position());
		System.out.println(buffer.limit());

		byte[] vArray = new byte[remaining];
		ByteBuffer bb = buffer.get(vArray);
		String dcode = new String(vArray);
		System.out.println(dcode);
	}
}

以上代码的结果:

88
12
88
===================
88
0
12

权威指南

1、从代码运行结果可以分析出,开始初始化capacity,position,limit分别是88,12,88,

2、从源码角度解析:
a、  public static ByteBuffer allocate(int capacity) {
        if (capacity < 0)
            throw new IllegalArgumentException();
        return new HeapByteBuffer(capacity, capacity);
    }

执行new HeapByteBuffer(capacity, capacity); capacity赋值为88,limit为88
执行buffer.put(value.getBytes()); position(position() + length);将position赋值为12

b、flip()方法实现: 
<pre name="code" class="java"> public final Buffer flip() {
        limit = position;
        position = 0;
        mark = -1;
        return this;
    }
将limit赋值为12,position赋值为0,这样就可以正确读取数据
之前put的时候发生:
 public ByteBuffer put(byte[] src, int offset, int length) {
        checkBounds(offset, length, src.length);
        if (length > remaining())
            throw new BufferOverflowException();
        int end = offset + length;
        for (int i = offset; i < end; i++)
            this.put(src[i]);
        return this;
    }

这里的end是12
读取的时候也要从0,12开始读取,不然会错误读,以下是读取源码:
   public ByteBuffer get(byte[] dst, int offset, int length) {
        checkBounds(offset, length, dst.length);
        if (length > remaining())
            throw new BufferUnderflowException();
        int end = offset + length;
        for (int i = offset; i < end; i++)
            dst[i] = get();
        return this;
    }





 







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值