2012-12-20 17 views
-4

如何將char數組寫入到java socketchannel中。因爲它需要ByteBuffer,所以我無法將char數據寫入socketchannel。如何將char數組寫入到java socketchannel中

+0

請提供一些代碼,你的問題。 –

+1

請參閱:http://stackoverflow.com/questions/871870/how-to-write-data-to-socket-channel。 –

回答

0

您是否嘗試過使用ByteBuffer的putChar方法?

ByteBuffer buf = ByteBuffer.allocate(1024); 

for (char ch : myChars) { 
    buf.putChar(ch); 
} 
0

幾種方法,例如

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

ByteBuffer.wrap(str.getBytes()); 
+0

只能發表評論,你可能希望明確說明你用什麼字符集來編碼你的字符數組,而不是僅僅使用默認的字符集。你的服務器可能期待一個特定的服務器,而你不想成爲任何平臺和語言環境正在運行你的代碼的突發事件的犧牲品。 – Charlie