Getting string from netty ByteBuf

2020-07-06 05:39发布

How can I get the string from a netty ByteBuf? As of now I am able to get it character by character. Is there a way to get the string object directly?

// message is of type ByteBuf
for (int i = 0; i < message.capacity(); i++) {
    byte b = message.payload().getByte(i);
    System.out.print((char) b);
}

3条回答
看我几分像从前
2楼-- · 2020-07-06 06:36

Use the provided method ByteBuf.toString(Charset) .

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-07-06 06:41

Take a look at this

From there you can use new String(byte[]) or some Base64 solution (since it's binary data I'm assuming)

查看更多
戒情不戒烟
4楼-- · 2020-07-06 06:42

use ByteBuf.readCharSequence()

example is here:

// here we use utf-8 decoding, you can choose the charset you want
String s = ByteBuf.readCharSequence(length, Charset.forName("utf-8")).toString()

note that ByteBuf.readCharSequence() returns java.lang.CharSequence, use toString() to get String obejct

查看更多
登录 后发表回答