-4

how to write char array to java socketchannel. I am not able to write the char data to socketchannel as it takes ByteBuffer.

Prithvi
  • 3
  • 1

2 Answers2

0

Have you tried using putChar method of ByteBuffer?

ByteBuffer buf = ByteBuffer.allocate(1024);

for (char ch : myChars) {
  buf.putChar(ch);
}
Andrey Adamovich
  • 20,285
  • 14
  • 94
  • 132
0

Several ways eg

char[] c = {'1', '2'};
String str = new String(c);
ByteBuffer bb = Charset.defaultCharset().encode(str);

or

ByteBuffer.wrap(str.getBytes());
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Only comment, more than likely you'll want to be explicit about what character set you are using to encode your character array instead of just using the default charset. Your server is probably expecting a specific one, and you don't want to be prey to the whims of whichever platform and locale is running your code. – Charlie Dec 20 '12 at 07:54