我坚持这个奇怪的问题。我正在做的是通过蓝牙通信2个设备。当我发送像ßàæé这样的特殊字符时,我会收到像这样的问号?????在另一台设备上。这是接收方的代码
private class ConnectedThread extends Thread {
private final Socket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(Socket socket) {
Log.d("ConnectionService", "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.d("ConnectionService", "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i("ConnectionService", "BEGIN mConnectedThread");
byte[] buffer = new byte[4096];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
if(bytes==0){
break;
}
String message = new String(buffer, 0, bytes);
Log.d("PC-DATA", message);
inputAnalyzer(message);
} catch (IOException e) {
Log.d("ConnectionService", "disconnected", e);
connectionLost();
break;
}
}
connectionLost();
}
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
} catch (IOException e) {
Log.d("ConnectionService", "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
connection = false;
} catch (IOException e) {
Log.d("ConnectionService", "close() of connect socket failed",
e);
}
}
}
从输入流读取后,我以这种方式将缓冲区转换为String。
String message = new String(buffer, 0, bytes);
这是错的还是我错过的其他东西! 有什么帮助吗?
答案 0 :(得分:1)
String message = new String(buffer, 0, bytes);
永远不要将字节转换为字符表示而不提及正确的字符集。请改用它。
String(byte[] bytes, int offset, int length, String charsetName)
UTF-8应该能够显示大多数特殊字符。如果它不适合您的情况,请使用涵盖您希望客户接收的字符的字符集。