Netty学习笔记二十四、Netty ByteBuf 代码

package com.hao.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

/**
 * @author haoxiansheng
 * @date 2020-05-24
 */
public class NettyByteBuf01 {
    public static void main(String[] args) {


        /**
         * 创建一个ByteBuf
         * 1、创建 对象 该对象包含一个数组arr,是一个byte[10]
         * 2、在netty 的buffer中不需要使用flip进行读写切换
         *   因为底层 维护了readerIndex 和 writerIndex
         * 3、通过readerIndex 和 writerIndex capacity将buffer分成了三个区域
         *      0 --- readerIndex 已经读取的区域
         *      readerIndex ---- writerIndex 可读的区域
         *      writerIndex ----- capacity 可写入的区域
         */
        ByteBuf byteBuf = Unpooled.buffer(10);

        for (int i = 0; i < 10; i++) {
            byteBuf.writeByte(i);
        }

        System.out.println("capacity" + byteBuf.capacity());
        // 输出
        for (int i = 0; i < byteBuf.capacity(); i++) {
            //System.out.println(byteBuf.getByte(i));
            System.out.println(byteBuf.readByte()); // 这个readerIndex 会逐渐变大
        }
    }
}


package com.hao.netty.buf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

/**
 * @author haoxiansheng
 * @date 2020-05-24
 */
public class NettyByteBuf02 {
    public static void main(String[] args) {
        // 创建 ByteBuf
        ByteBuf byteBuf = Unpooled.copiedBuffer("hello ,world", Charset.forName("utf-8"));
        // 使用相关的方法
        if (byteBuf.hasArray()) { // true
            byte[] content = byteBuf.array();
            // 将content 转成字符串
            System.out.println(new String(content, Charset.forName("utf-8")));
            System.out.println(byteBuf.readerIndex()); // 0
            System.out.println(byteBuf.arrayOffset()); // 0
            System.out.println(byteBuf.readerIndex()); // 12
            System.out.println(byteBuf.capacity()); // 36

            int len = byteBuf.readableBytes(); // 返回可读区的字节数 12
            System.out.println(len);
            System.out.println(byteBuf.getCharSequence(0, 4, CharsetUtil.UTF_8));

        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值