我过去在这里找到了许多很好的答案后才加入 StackOverflow。这是我的第一个问题:
编辑:我感觉很糟糕……我向 StackOverflow 提出的第一个问题结果是“徒劳的追逐”。问题出在数据,而不是读取数据的代码。我在错误的地方寻找解决方案!我将在下面的评论中解释。
请忽略此问题。
在我的应用程序中,数据以片段的形式到达(它是串行数据)。我想将数据传递给将解析它的方法。但我只想传递正确终止的行。这些行将以“\r”(返回字符)终止。有时进来的数据片段有多个终止行。但有时进来的数据片段还没有终止符(终止符稍后到达)。
我的目标是能够仅将正确终止的行(完整行)发送到 dataProcessor.logSerialData。 (代码可以在没有这个要求的情况下工作,但如果我能满足这个要求,我可以编写更简洁的代码。解析逻辑——这里没有显示——会更容易维护。)
这是我的有效代码(但不符合我的新要求):
case SerialPortEvent.DATA_AVAILABLE:
try
{
int len = -1;
while ((len = in.read(readBuffer)) > 0)
{
if (len > 0)
{
String s = new String(readBuffer, 0, len);
if (dataProcessor != null)
{
dataProcessor.logSerialData(s);
}
else
{
Logger.log("ERROR: packetReceiver is null");
}
}
}
}
catch (IOException ex)
{
Logger.log(ex);
return;
}
这是我尝试过的许多无效方法之一的示例。它以某种方式导致数据流中的错误。
private static final String REGEX = ".*\\r";
private Pattern p = Pattern.compile(REGEX);
public void serialEvent(SerialPortEvent e)
{
byte[] readBuffer = new byte[11000];//tried many values for buffer size
switch (e.getEventType())
{
case SerialPortEvent.DATA_AVAILABLE:
try
{
int len = -1;
while ((len = in.read(readBuffer)) > 0)
{
if (len > 0)
{
String input = new String(readBuffer, 0, len);
Matcher m = p.matcher(input);
int count = 0;
while (m.find())
{
count++;
String terminatedLine = m.group();
if (!terminatedLine.isEmpty())
{
completedLines.add(terminatedLine);
}
}
}
}
}
catch (IOException ex)
{
Logger.log(ex);
return;
}
for (String line : completedLines)
{
dataProcessor.logSerialData(line);
}
有什么建议吗? (事实上,知道为什么新代码会在数据流中引入错误吗?我尝试过的工作代码的每个变体都无法正常工作。我已经尝试过正则表达式和非正则表达式方法以及任何其他方法。唯一的代码works 是上面显示的工作示例。串行数据处理似乎非常棘手!我需要一些帮助。
最佳答案
这应该可以根据需要工作。
private String remains = "";
...
int len = -1;
while ((len = in.read(readBuffer)) > 0) {
if (len > 0) {
String input = remains + new String(readBuffer, 0, len);
Matcher m = p.matcher(input);
int last = 0;
while (m.find()) {
String terminatedLine = m.group();
last = m.end(0);
if (!terminatedLine.isEmpty()) completedLines.add(terminatedLine);
}
remains = input.substring(last);
}
}
关于Java:如何将传入的数据片段收集到正确终止的字符串中以供后续解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3840424/