2015-03-19 125 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