【问题标题】:how to write char array to java socketchannel如何将char数组写入java socketchannel
【发布时间】:2012-12-20 07:38:53
【问题描述】:

如何将 char 数组写入 java socketchannel。我无法将 char 数据写入 socketchannel,因为它需要 ByteBuffer。

【问题讨论】:

标签: java socketchannel


【解决方案1】:

你试过用putChar ByteBuffer的方法吗?

ByteBuffer buf = ByteBuffer.allocate(1024);

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

【讨论】:

    【解决方案2】:

    几种方式,例如

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

    ByteBuffer.wrap(str.getBytes());
    

    【讨论】:

    • 仅注释,您很可能希望明确说明您使用什么字符集对字符数组进行编码,而不仅仅是使用默认字符集。您的服务器可能需要一个特定的服务器,并且您不想成为运行代码的平台和区域设置的猎物。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    相关资源
    最近更新 更多