0

我被困在这个奇怪的问题上。我正在做的是通过蓝牙与 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 message = new String(buffer, 0, bytes);

这是错误的还是我缺少的其他东西!有什么帮助吗?

4

1 回答 1

1
String message = new String(buffer, 0, bytes);

切勿在不提及正确字符集的情况下将字节转换为字符表示。改用这个。

String(byte[] bytes, int offset, int length, String charsetName)

UTF-8 应该能够显示大多数特殊字符。如果它不适合您的情况,请使用涵盖您希望客户端接收的字符的字符集。

于 2013-03-19T17:25:39.573 回答