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

 

posted on 2019-09-05 11:46  Deltadeblog  阅读(21671)  评论(0编辑  收藏  举报

导航