java 从 netty ByteBuf 获取字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38164891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting string from netty ByteBuf
提问by aries
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?
如何从 netty 获取字符串ByteBuf
?到目前为止,我可以逐个字符地获取它。有没有办法直接获取字符串对象?
// message is of type ByteBuf
for (int i = 0; i < message.capacity(); i++) {
byte b = message.payload().getByte(i);
System.out.print((char) b);
}
回答by mileippert
Use the provided method ByteBuf.toString(Charset) .
使用提供的方法ByteBuf.toString(Charset)。
回答by xinnjie
use ByteBuf.readCharSequence()
利用 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
请注意,ByteBuf.readCharSequence()
返回java.lang.CharSequence
,用于toString()
获取String
对象
回答by cilki
From there you can use new String(byte[])
or some Base64 solution (since it's binary data I'm assuming)
从那里你可以使用new String(byte[])
或一些 Base64 解决方案(因为它是我假设的二进制数据)