2013-03-19 136 views
0

我困在這個奇怪的問題上。我正在做的是通過藍牙通信2臺設備。當我發送像ßàæé這樣的特殊字符時,我會收到像這樣的問號?????在另一臺設備上。下面是從輸入流i轉換成緩衝字符串以這種方式讀出後,在接收側將特殊字符轉換爲字符串

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); 

這是錯誤還是其他我錯過了! 有什麼幫助嗎?

+0

你在哪裏看到問號?在實際數據中,還是在打印數據時記錄/屏幕?您的字體可能只是沒有在第二種情況下定義的那些字符。 – 2013-03-19 17:23:03

+0

在實際數據中。 – Ahmed 2013-03-19 18:55:39

回答

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

不要將字節轉換爲字符表示而不提及正確的字符集。改用它。

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

UTF-8應該能夠顯示大多數特殊字符。如果它不適合您的情況,請使用涵蓋您希望客戶收到的字符的字符集。

+0

謝謝你的回答,我嘗試了所有這些,但沒有在我的情況下工作。 US-ASCII現在\t ISO-8859-1 \t UTF-8 UTF-16BE UTF-16LE UTF-16 – Ahmed 2013-03-19 18:50:40

+0

由於其工作。我從服務器端犯了錯誤。我用ASCII編碼它。現在我正在使用UTF-8,現在它的工作很好。 – Ahmed 2013-03-19 19:37:20

相關問題