java目录更改当前_Java-MVC:查看目录更改的最佳方法
我將使用的方法是在WatchDir中提供用于注冊回調的方法.最簡單的方法是對回調使用
Consumer屬性:
public class WatchDir {
private Consumer onCreate ;
public void setOnCreate(Consumer onCreate) {
this.onCreate = onCreate ;
}
// other callbacks as needed...
// ...
void processEvents() {
// ...
Path child = ... ; // file/folder that was created
if (! recursive && kind == ENTRY_CREATE) {
if (onCreate != null) {
onCreate.accept(child);
}
}
// ...
}
// ...
}
請注意,WatchDir.processEvents()是(非終止)阻塞調用,因此您需要在后臺線程中運行它.因此,您可以從控制器中執(zhí)行以下操作:
WatchDir watchDir = new WatchDir(rootPath, false) ;
watchDir.setOnCreate(path ->
Platform.runLater(() -> listView.getItems().add(path)));
Thread watchThread = new Thread(watchDir::processEvents);
watchThread.setDaemon(true);
watchThread.start();
請注意,由于回調將在后臺線程上調用,因此對UI的更新應包裝在Platform.runLater(…)中.如果愿意,可以為WatchDir配備執(zhí)行程序來執(zhí)行回調,這使您僅需告訴一次即可始終通過Platform.runLater(…)執(zhí)行回調:
public class WatchDir {
// Executor for notifications: by default just run on the current thread
private Executor notificationExecutor = Runnable::run ;
public void setNotificationExecutor(Executor notificationExecutor) {
this.notificationExecutor = notificationExecutor ;
}
private Consumer onCreate ;
// etc...
void processEvents() {
// ...
if (! recursive && kind == ENTRY_CREATE) {
if (onCreate != null) {
notificationExecutor.execute(() -> onCreate.accept(child));
}
}
// ...
}
}
接著
WatchDir watchDir = new WatchDir(rootPath, false) ;
watchDir.setNotificationExecutor(Platform::runLater);
watchDir.setOnCreate(listView.getItems()::add); /* or path -> listView.getItems().add(path) */
Thread watchThread = new Thread(watchDir::processEvents);
watchThread.setDaemon(true);
watchThread.start();
總結
以上是生活随笔為你收集整理的java目录更改当前_Java-MVC:查看目录更改的最佳方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 歌词爱我的人是哪首歌啊?
- 下一篇: java json发送文件_关于java