10

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);
}
bcsb1001
  • 2,834
  • 3
  • 24
  • 35
aries
  • 849
  • 3
  • 11
  • 24

3 Answers3

14

Use the provided method ByteBuf.toString(Charset) .

mileippert
  • 177
  • 8
4

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

xinnjie
  • 672
  • 5
  • 12
0

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)

Community
  • 1
  • 1
cilki
  • 125
  • 1
  • 13