2015-03-19 37 views
0

嵌入式系統項目中,我將得到我的微控制器到Android設備使用藍牙模塊的一些反應,我不能得到這一行的字節bytes = "mmInStream.read(buffer)" .. 當我轉換字節[]緩衝成字符串使用這個 String data=new String(bytes)我沒有得到我從我的微控制器正確發送的數據。有時charactors缺少..Java輸入流讀取()沒有得到完整的字節陣列數據

 public void run() { 
     Log.i(TAG, "BEGIN mConnectedThread"); 
     byte[] buffer = new byte[1024]; 
     int bytes; 

     // Keep listening to the InputStream while connected 
     while (true) { 
      try { 
       // Read from the InputStream 
       bytes = mmInStream.read(buffer); 

       String data=new String(bytes);   
       System.out.println(data);   

       // Send the obtained bytes to the UI Activity 

      } catch (IOException e) { 
       Log.e(TAG, "disconnected", e); 
       connectionLost(); 
       break; 
      } 
     } 
    } 

請幫我

+0

使用新的字符串(緩衝區,0,字節)而不是新的字符串(字節),並且數據應該正確顯示 – Paul 2015-03-19 11:39:26

回答

0

嘗試使用BufferedReader代替。

它從一個字符輸入流中讀取文本,緩衝字符,從而 作爲提供的字符,數組和 線的高效讀取。

如果您使用Java 7或更早下面的代碼將有助於:

try (BufferedReader reader = new BufferedReader(new InputStreamReader(mmInStream))){ 
     String line = null; 
     while((line = reader.readLine()) != null) { 
     System.out.println(line); 
     } 
     connectionLost(); 
    } catch(IOException e) { 
     e.printStackTrace(); 
    } 

如果你使用Java 6或年齡小於使用此代碼:

BufferedReader reader = null; 
    try { 
     reader = new BufferedReader(new InputStreamReader(mmInStream)); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
     System.out.println(line); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (reader != null) { 
     try { 
      reader.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     } 
     connectionLost(); 
    } 

但這種方法有缺點。你可以閱讀它們,例如here