我有一个通过rxtx读取串口的代码。但我希望输入流的缓冲读取器应检查数据即将到来的指定时间。超时后,它应该停止我已经开始读取serialReader的程序或线程。
答案 0 :(得分:0)
你可以这样做:
clear()
刚开始的大纲。读操作将在单独的线程上完成。然后在你的主线程上等待它完成,捕获一个TimeoutException。如果发生这种情况,您可以清理资源(关闭COM端口!!)并退出。如果没有发生,则读取成功。
一些资源:
根据您的代码:
ExecutorService exec = new Executors.newSingleThreadExecutor();
// ... where you want to start reading and wait:
Future<String> readResult = exec.submit( new Callable<String>(){
@Override public String call(){
// Your reading code here.
}
} );
try{
String strResult = readResult.get( 1, TimeUnit.MINUTES );
} catch(TimeoutException tex) {
// handle Timeout
} catch ( /*... you should also catch other exceptions like */ IOException ioex ){}
请注意,我没有使用IDE来编写或编译它,可能存在拼写错误,需要进行一些调整。
答案 1 :(得分:0)
public ReadWithoutTimings() {
super();
num = 1;
try {
try {
serialPort = (SerialPort) portId.open("Read1", 2000);
} catch (PortInUseException e) {
System.out.println(e);
JOptionPane.showMessageDialog(null, e);
}
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e1) {
System.out.println(e1);
}
try {
in = serialPort.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*timer.schedule(new TimerTask() {
@Override
public void run() {
(new Thread(new SerialReader(in))).start();
}
}, time);*/
(new Thread(new SerialReader(in))).start();
}
public class SerialReader implements Runnable {
public SerialReader(InputStream in) {
inputStream = in;
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
br = new BufferedReader(new InputStreamReader(inputStream));
try {
bw = new BufferedWriter(new FileWriter(FILENAME));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
String inputLine = null;
try {
while ((inputLine = br.readLine()) != null) {
//series.put(num, inputLine);
//num++;
bw.write(inputLine);
bw.newLine();
bw.flush();
System.out.println(inputLine);
if (inputLine.trim().startsWith("DATE") | inputLine.trim().startsWith("REMARK")
| inputLine.trim().startsWith("TESTED BY")) {
serialPort.close();
inputStream.close();
br.close();
bw.close();
break;
}
}
//new CompareClass();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
答案 2 :(得分:-1)
可能将Timer(Schedule)与读取循环结合使用。
使用如下 - &gt; timer.schedule(&#39; your_read_task&#39;&#39; time_when_you_want_to_end&#39)