how to write char array to java socketchannel. I am not able to write the char data to socketchannel as it takes ByteBuffer.
Asked
Active
Viewed 638 times
-4
-
Please provide some code to your question. – jens-na Dec 20 '12 at 07:43
-
1See: http://stackoverflow.com/questions/871870/how-to-write-data-to-socket-channel. – Adrian Ber Dec 20 '12 at 07:47
2 Answers
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