将字节从串行传输保存到字符串

Save Bytes from Seral Transfer to String

我有以下代码,我正在尝试将接收到的字节保存到一个字符串中,直到我收到 \n。

 byte[] buffer = new byte[1024];
                int bytes;
                String ReceivedMessage = null;
                while (true) {

                    try

 {
                        // Read from the InputStream
                        bytes = mmInStream.read(buffer);

                        ReceivedMessage = ReceivedMessage + getString(bytes);
                        // Send the obtained bytes to the UI Activity
                        if(ReceivedMessage.endsWith("\n")) {
                            String StringToReturn = ReceivedMessage.replace("\n","");

                            Message msg = mHandler.obtainMessage(AbstractActivity.MESSAGE_READ);
                            Bundle bundle = new Bundle();
                            bundle.putString("Message", StringToReturn);
                            msg.setData(bundle);
                            mHandler.sendMessage(msg);

                            //mHandler.obtainMessage(AbstractActivity.MESSAGE_READ, bytes, -1, buffer)
                            //        .sendToTarget();
                        }

                } catch (IOException e) {
                    e.printStackTrace();
                    connectionLost();
                    BluetoothService.this.stop();
                    break;
                }

问题是它在 ReceivedMessage = ReceivedMessage + getString(bytes); 上崩溃,更准确地说是在 getString(bytes)

上崩溃

你能帮我解决一下吗?

谢谢!

正在编辑这个,因为我不能post 评论:

您只能读取一次缓冲区并且

字节 = mmInStream.read(缓冲区);

如果确实是同一个缓冲区,则读取内容。不好说。

while(true)也意味着这最终会触发异常。

[编辑]

堆栈跟踪是什么? getString 调用什么?为什么你用"while (true)"没出路?您是否尝试从 StreamBuffer 读取两次?

(这将是一个评论,但没有得到足够的代表)

String TempString = new String(buffer,0,bytes);
ReceivedMessage = ReceivedMessage + TempString;