栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Netty 池化工具类——Unpooled 的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Netty 池化工具类——Unpooled 的使用

Netty 中提供了替代 NIO 中的 ByteBuffer 池化工具类,如下所示:

package main;

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

import java.nio.charset.Charset;

public class UnpooledDemo1 {


    public static void main(String[] args) {
        
        ByteBuf buffer = Unpooled.buffer(10);
        for (int i = 0; i < 10; i++) {
            buffer.writeByte(i);
        }
        for (int i = 0; i < 10; i++) {
            System.out.println(buffer.readByte());
        }
        
        ByteBuf buf = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);

        if (buf.hasArray()) {
            byte[] content = buf.array();
            System.out.println(new String(content, Charset.forName("UTF-8")));
            System.out.println(buf.arrayOffset());
            System.out.println(buf.readerIndex());
            System.out.println(buf.writerIndex());
            System.out.println(buf.capacity());
            System.out.println(buf.getByte(1));
            System.out.println(buf.readByte());
            System.out.println(buf.readableBytes());

            int len = buf.readableBytes();
            for (int i = 0; i < len; i++) {
                System.out.println((char)buf.readByte());
            }
        }
    }
}

运行结果:

0
1
2
3
4
5
6
7
8
9
hello world
0
0
11
33
101
104
10
e
l
l
o
 
w
o
r
l
d
Process finished with exit code 0

然后在回忆下 NIO 中同的 Buffer 类,代码如下:

    public static void main1(String[] args) {

        IntBuffer allocate = IntBuffer.allocate(5);

        allocate.put(30);
        allocate.put(34);

        Buffer flip = allocate.flip();

        while (flip.hasRemaining()) {
            System.out.println(allocate.get());
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1035600.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号