int字节到java中的字符串

时间:2012-11-11 20:20:03

标签: android sockets bytearray

问题

我在socket客户端读取第一个字节以检查连接:

ByteBuffer b = ByteBuffer.allocate(4);
b.order(ByteOrder.BIG_ENDIAN);
...
int dataInt = clientSocket.getInputStream().read();

文档

  

从此流中读取单个字节并将其作为整数返回   范围从0到255.如果流的末尾已经返回-1   达到。

之后我想用下一个输入字符串拼接这个字节。我将这个整数字节转换为字符

b.putInt(dataInt);
byte[] dataByte = b.array();
final String data;

并检查它。如果dataInt!= -1,我必须将这个croped字节返回到新字符串:

if(dataInt != -1)
{
    String c = new String(dataByte);
    Log.v("MSG", c);
    data = c + inToServer.readLine();
}
else
{
    data = inToServer.readLine();
}

为什么我在日志中看到“MSG, MYMESSAGE”?如何正确获取字符串?


更新,我如何发送消息:

byte[] buf = str.getBytes("UTF-8");
outToServer.write(buf, 0, buf.length);
outToServer.writeBytes("\n");
outToServer.flush();

4 个答案:

答案 0 :(得分:2)

if(dataInt != -1)
{
    String c = new String(dataByte, "UTF-8");
    Log.v("MSG", c);
    data = c + inToServer.readLine();
}
else
{
    data = inToServer.readLine();
}

答案 1 :(得分:1)

好的,所以在服务器端只需用收到的字节[]执行此操作。不需要字节缓冲区,也不需要以任何方式操作它。

String str = new String(recievedBytes); 

答案 2 :(得分:0)

我建议您使用IOUtils.toString。它有助于进行大量无聊且容易出错的输入/输出流操作。

以下是解释how to setup your project to use apache IO commons的答案。

答案 3 :(得分:0)

哦,我做到了。 解决方案:

byte[] b1 = new byte[1];
int dataInt = clientSocket.getInputStream().read();
b1[0] = (byte)dataInt;