2013-11-04 41 views
0

服务器接收字节数组作为输入流,然后用DataInputStream封装流。前2个字节表示字节数组的长度,第2个字节表示一个标志,下一个字节包含content.My问题是内容包含有2个字节的unicode字符。如何读取unicode字符?我的上一个代码是:Java如何读取套接字中的unicode字符?

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的帮助!

+0

见BalusC答案这里:http://stackoverflow.com/questions/4505057/datainputstream-and-utf-8 –

+0

又见[ readChar](http://docs.oracle.com/javase/7/docs/api/java/io/DataInputStream.html#readChar())方法,如果这些代码点是big-endian UTF-16。 – McDowell

+0

thx太多了。答案解决了我的问题。 –

回答

0

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

+0

我已经解决了我的问题:String s = new String(bytes,“UTF-8”);我认为它与你的解决方案〜thx相似 –