2013-03-14 73 views
0

我试图使用Android的样本BlueToothChat每次但有件事我不明白:的getBytes的toString不会产生相同的结果

byte[] send = message.getBytes(); 
Log.d("SEND_BYTE", send.toString()); 
mChatService.write(send); 

这里,消息是一个字符串,然后转换为字节,我想为了被发送。但是当我检查日志时,即使我输入的消息很长,send.toString()部分也非常短。更糟糕的是,如果我输入两次相同的信息,我会得到2个不同的日志,我发现这很奇怪。 下面是我得到的日志中的消息hello,连续三次:

[[email protected] 
[[email protected] 
[[email protected] 

一定有什么东西(也许很简单的),我没有得到,但可以(T弄清楚什么是你能不能帮我这个

编辑:? 也许是有用的添加代码的下面,所以在这里是完整的代码:

byte[] send = message.getBytes(); 
Log.d("SEND_BYTE", send.toString()); 
mChatService.write(send); 

// Reset out string buffer to zero and clear the edit text field (buffer is used in the write function) 
mOutStringBuffer.setLength(0); 
mOutEditText.setText(mOutStringBuffer); 
+1

默认的toString方法返回的getClass()的getName()+ '@' + Integer.toHexString(hashCode()方法) – 2013-03-14 10:55:09

回答

6

是的,在字节数组上调用toString()是个坏主意。数组不会覆盖toString(),因此您将获得默认行为Object.toString()

要扭转String.getBytes()电话,你想:

Log.d("SEND_BYTE", new String(send)); 

还是看字节更直接:

Log.d("SEND_BYTE", Arrays.toString(send)); 

然而,我会强烈建议您做直。相反,您应该在转换为二进制文件或从二进制文件转换时指定编码,否则将使用平台默认编码。聊天服务期待什么编码?例如,如果该公司预计,UTF-8:

byte[] send = message.getBytes("UTF-8"); 
Log.d("SEND_BYTE", Arrays.toString(send)); 
mChatService.write(send); 
+0

非常感谢,您的解决方案完美无缺 – WhiskThimble 2013-03-14 11:10:04

1

您需要创建一个新的字符串对象得到实际的字符串

String senddata=new String(send); 
1

尝试:

Log.d("SEND_BYTE", new String(send, "UTF-8");); 
相关问题