Java如何在socket中读取unicode字符?

时间:2013-11-04 09:25:08

标签: java sockets unicode

服务器接收字节数组作为输入流,我用DataInputStream包装流。前2个字节表示字节数组的长度,后2个字节表示一个标志,下一个字节由内容组成。我问题是内容包含有2个字节的unicode字符。如何读取unicode char?我的优惠代码是:

    DataInputStream dis = new DataInputStream(is);
    int length = dis.readUnsignedShort();
    int flag = dis.readUnsignedShort();

    String content = "";
    int c;
    for (int i = 0; i < length - 4; i++) {
        c = dis.read();
        content += (char) c;
    }

它只能为你的帮助读取ascII.thxs!

1 个答案:

答案 0 :(得分:0)

这取决于输入的编码方案。如果您不想进行繁重的工作,可以使用Apache IOUtils并将字节转换为unicode字符串。 示例:     IOUtils.toString(bytes,“UTF-8”)