我确实通过Java在Linux中读取了串行接口文件。有时我只需要丢弃所有数据并仅读取新内容。
说明:有大量数据,新数据即将来临,因此我必须丢弃现有缓冲区并开始等待新数据。外部板一直在发送。我最终读取了旧数据,仅经过几次迭代便获得了当前值。我只需要跳过结尾并仅等待新的数据集,而不是读取所有旧的废话即可。
String file = "/dev/ttyO1";
FileInputStream inputStream = new FileInputStream(file);
private static byte[] readUntil(InputStream in, int timeout) throws IOException {
// long lastTime = System.currentTimeMillis();
while (true) {
if (in.available() > 0) {
if (in.read() == 83)
break;
}
try { Thread.sleep(20); } catch (Exception e) {}
}
byte[] text = new byte[10];
for (int i = 0; i < 10; i++) {
text[i] = (byte) in.read();
if (text[i]=="E".getBytes()[0]) break;
try { Thread.sleep(20); } catch (Exception e) {}
}
in.read(); // just read last one
return text;
}
我只是无法弄清楚如何丢弃现有数据并仅读取新数据。
我不确切知道什么是“ Linux中的串行接口文件”。但是我认为这是一个简单的文件,一直都有附加的文本,您想等待附加的新内容,而不是从头开始读取整个文件。您可以使用RandomAccessFile
类的seek(long)
方法来跳过数据。或者,您可以在到达文件末尾时睡一会儿。
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("src/file.txt");
int i = 0;
while (i < 50) { // read only 50 bytes
byte b = (byte)fis.read();
if (b == -1) { // end of file, wait
Thread.sleep(500L);
continue;
}
System.out.print((char) b);
i++;
}
fis.close();
}
这只是一个简单的例子。我最多只能读取50个字节,但您想读取的内容远不止于此。也许您可以使用超时。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句