我正在构建一个SWT应用程序,它将触发一个长时间运行的shell进程。我能够在这个Java Lobby链接中提到的单独线程中触发它。
我的shell进程将生成一个日志文件。我必须阅读它并在文本区域显示该过程的进度。如何在不阻塞UI线程的情况下实现它。
答案 0 :(得分:0)
就像您分享的链接一样,您需要在单独的线程中启动日志观察器:
Thread one = new Thread(){
public void run() {
System.out.println("start watching log.");
updateLog();
}
};
one.start();
使用WatchService检测日志文件更改后,使用SWT的Display asyncExec显示日志更改:
WatchService watchService = FileSystems.getDefault().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
if (event.context().toString().endsWith(logfileName)) {
shlLogViewer.getDisplay().asyncExec(new Runnable() {
public void run() {
logDisplay.setText(readFromFile(LOG_FILE_SIZE));
}
});
}
}
key.reset();
Thread.sleep(1000);
}