netty ByteBuf与String相互转换


 

String转为ByteBuf

1)使用String.getBytes(Charset),将String转为byte[]类型

2)使用Unpooled.wrappedBuffer(byte[]),将byte[]转为ByteBuf

        String msg = "A message";
        byte[] bytes = msg.getBytes(CharsetUtil.UTF_8);
        ByteBuf buf = Unpooled.wrappedBuffer(bytes);

 

或者使用 Unpooled.copiedBuffer(CharSequence string, Charset charset)

ByteBuf buf = Unpooled.copiedBuffer("Hello", CharsetUtil.UTF_8);

 

 

ByteBuf转为String

使用ByteBuf.toString(Charset),将ByteBuf转为String

buf.toString(CharsetUtil.UTF_8)

 

 

示例:

        String msg = "A message";
        byte[] bytes = msg.getBytes(CharsetUtil.UTF_8);
        ByteBuf buf = Unpooled.wrappedBuffer(bytes);
        System.out.println(buf.toString(CharsetUtil.UTF_8));

输出:A message

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM