我需要在Web应用程序的两个目录中监视更改(上载的文件)。我创建了一个ServletContextListener来触发对这两个目录的监视。
我的问题是,当第一次监控开始时,线程被阻塞,第二次监控没有启动。
是否可以保持两个不同文件夹的监控并行和后台运行?
我知道问题是由于无限循环,但不知道如何将此线程放在后台。任何帮助将不胜感激 。非常感谢您提前
ContextListener
@Override
public void contextInitialized(ServletContextEvent event) {
Path pathFolder1 = Paths.get("my_folder_1_path");
MyWatcher watcher1 = new MyWatcher();
Path pathFolder2 = Paths.get("my_folder_2_path");
MyWatcher watcher2 = new MyWatcher();
watcher1.startMonitoring(pathFolder1);
watcher2.startMonitoring(pathFolder2);
}
MyWatcher
public void startMonitoring(Path directory) {
try {
FileSystem fs = directory.getFileSystem ();
WatchService watcher = fs.newWatchService();
while(true) {
directory.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
WatchKey watckKey = watcher.take();
List<WatchEvent<?>> events = watckKey.pollEvents();
for (WatchEvent event : events) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("File created: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("File removed: " + event.context().toString());
}
}
watckKey.reset();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}