我确实通过Java读取Linux中的串行接口(interface)文件。有时我只需要丢弃所有数据并只读取新数据。
解释:有大量数据并且新数据即将到来,因此我必须丢弃现有缓冲区并开始等待新数据。外部板只是不断发送。我最终读取了旧数据,仅经过几次迭代,我就获得了当前值。我只需跳到结尾并等待新的数据集,而不是读取所有旧的废话。
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 上,在 C 程序中,you would be able to do :
tcflush(fd, TCIFLUSH)
刷新传入缓冲区。但您无法直接从 Java 执行此操作 - 它不是独立于平台的功能。
您可以编写一个小型 C 程序来执行此操作,然后将数据从 /dev/ttyO1
通过管道传输到 stdout。您可以使用 ProcessBuilder
从 Java 代码启动该程序并读取其数据,而不是直接读取串行端口。
再想一想,您不需要 C 程序执行任何管道操作,您只需要调用它一次,然后就可以从 Java 打开 /dev/tty01
。
这是一个小型 C 程序,可以执行此操作:
#include <sys/types.h>
#include <sys/stat.h>
#include <termios.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv) {
int i;
for (i = 1; i < argc; i++) {
int fd = open(argv[i], O_NOCTTY, O_RDONLY);
if (fd >= 0) {
int result = tcflush(fd, TCIFLUSH);
close(fd);
if (result == -1) {
fprintf(stderr, "%s: Couldn't open file %s; %s\n",
argv[0], argv[i], strerror(errno));
exit (EXIT_FAILURE);
}
} else {
fprintf(stderr, "%s: Couldn't open file %s; %s\n",
argv[0], argv[i], strerror(errno));
exit (EXIT_FAILURE);
}
}
}
使用gcc -o tcflush tcflush.c
编译并使用tcflush/dev/tty01
运行。
关于java - java中读取到文件末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23288595/