case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[64];
try {
// read data
int numBytes = inputStream.read(readBuffer);
inputStream.close();
//-------------------------------
//send the received data to the GUI
String result = new String(readBuffer,0,numBytes);
//-----------------------------
gui.setjtaReceived(result);
matcher(result,writer,df);
//gui.setjtaReceived(result);
}
catch (IOException e) {exceptionReport(e);}
在上述 SerialPortEvent.Dat_Available 的切换案例中,我正在实时接收连续数据。匹配器函数调用下面定义的函数
private void matcher(String str,FileWriter writer,DateFormat df) {
Matcher m1 = p1.matcher(str);
Matcher m2 = p2.matcher(str);
System.out.println(m1.group());
Calendar cal = Calendar.getInstance();
String match_heartBeat = null;
String match1 = m1.group();
int length1 = match1.length();
if(m2.find()){
String match2 = m2.group();
int length2 = match2.length();
match_heartBeat = match2.substring(2, length2-1);
//System.out.println(match1.subSequence(2, 4) + ";" + match_heartBeat);
}
String realTime = df.format(cal.getTime());
writer.append(realTime);
writer.append(',');
writer.append(match1.subSequence(2, length1-1));
writer.append(',');
writer.append(match_heartBeat);
writer.append('\n');
writer.flush();
}
当我尝试写入外部 csv 文件或什至执行 System.out.println(m1.group) 或 System.out.println(match_heartBeat) 时,我无法将其写入文件或打印到屏幕。但是 System.out.println(m1) 打印在屏幕上。知道如何克服这个吗?我正在尝试解码实时接收到的数据。 模式如下:
Pattern p1 = Pattern.compile("\\b(a)\\w*( )\\b");
Pattern p2 = Pattern.compile("\\b(')\\w*( )\\b");
它查找字母表 'a' 直到空格和 ' 到空格。一旦程序开始运行,就会生成文件“writer”。但可以附加解码数据。
示例数据:
79 0009a017 009a047 9%0009a047 90009a046 9%0009a0469 0009a045 9%0009a0459'00 90009a045 9%0009a044 90009a044 9%0009a044 9
示例输出 CSV文件
System time , 17 , 00
最佳答案
让我们根据评论澄清规范。这是输入字符串:
79 0009a017 009a047
这是输出字符串:
017,00
而“017”是十进制(非八进制)数。稍后将其格式化为“17”可能会很方便。
如评论中所述,此正则表达式不正确:
Pattern p1 = Pattern.compile("\\b(a)\\w*( )\\b");
应该是:
Pattern p1 = Pattern.compile("a(\\d+) (\\d{2})");
快速演示:
echo "79 0009a017 009a047" | perl -lne 'print $1,",",$2 if /a(\d+) (\d{2})/'
017,00
关于java - 使用 GNU 读取连续数据时在尝试中调用匹配器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8634591/