【发布时间】:2011-05-13 19:41:07
【问题描述】:
我使用以下代码(来自蓝牙聊天示例应用程序)来读取传入数据并根据读取的字节构造一个字符串。我想读到这个字符串到达<!MSG>。如何用 read() 函数插入这个条件?
整个字符串看起来像这样<MSG><N>xxx<!N><V>yyy<!V><!MSG>。但是 read() 函数不会一次读取整个字符串。当我显示字符时,我看不到同一行中的所有字符。它看起来像:
发件人:<MS
发件人:G><N>xx
发件人:x<V
.
.
.
我在手机 (HTC Desire) 上显示字符并使用 Windows 超级终端发送数据。
如何确保所有字符都显示在一行中?我曾尝试使用 StringBuilder 和 StringBuffer 而不是 new String() 但问题是 read() 函数不会读取所有发送的字符。输入流的长度(字节)不等于发送的字符串的实际长度。从读取的字节构造字符串是正常的。
感谢您为此提供的任何建议和时间。如果有的话,也请随时提出其他错误或更好的方法。
干杯,
马杜
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
//Writer writer = new StringWriter();
byte[] buffer = new byte[1024];
int bytes;
//String end = "<!MSG>";
//byte compare = new Byte(Byte.parseByte(end));
// Keep listening to the InputStream while connected
while (true) {
try {
//boolean result = buffer.equals(compare);
//while(true) {
// Read from the InputStream
bytes = mmInStream.read(buffer);
//Reader reader = new BufferedReader(new InputStreamReader(mmInStream, "UTF-8"));
//int n;
//while ((bytes = reader.read(buffer)) != -1) {
//writer.write(buffer, 0, bytes);
//StringBuffer sb = new StringBuffer();
//sb = sb.append(buffer);
//String readMsg = writer.toString();
String readMsg = new String(buffer, 0, bytes);
//if (readMsg.endsWith(end))
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, readMsg)
.sendToTarget();
//}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
【问题讨论】:
标签: java conditional inputstream stringbuilder