我有一个监视服务,它监视目录ENTRY_DELETE
和事件ENTRY_CREATE
并ENTRY_MODIFY
根据事件执行逻辑。
我需要该服务来监视目录中的所有更改,而不是退出循环。但我还需要启动我的其他逻辑。
我怎样才能将这些方法重构为 aRunnable
来实现这一点?
如果代码如下。
public static void main(String[] args) {
System.out.println("Started watching");
FileServices fileServices = new FileServicesImpl();
fileServices.setSrcDir(fileServices.getValue("srcdir","properties/abc.properties"));
fileServices.setDestDir(fileServices.getValue("destdir","properties/abc.properties"));
System.out.println(fileServices.getSrcDir());
System.out.println(fileServices.getDestDir());
Map<String,WatchEvent> files = new HashMap<>();
MappingConsole mappingConsole = new MappingConsole();
for(;;){
files = fileServices.getEventMap();
for(String f : files.keySet()){
System.out.println("Size of files: "+files.size());
if (files.get(f).kind() == ENTRY_CREATE || files.get(f).kind() == ENTRY_MODIFY) {
System.out.println("Processing: " +f);
mappingConsole.map940(fileServices.getSrcDir(),f,fileServices.getDestDir());
System.out.println("Processed: " +f);
}
}
}
}
来自 FileServicesImpl:
@Override
public void monitorSrcDir(String srcDir){
for(;;){
try {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path myDir = Paths.get(srcDir);
WatchService watcher = myDir.getFileSystem().newWatchService();
myDir.register(watcher, ENTRY_CREATE,ENTRY_DELETE, ENTRY_MODIFY);
WatchKey watchKey = watcher.take();
List<WatchEvent<?>> events = watchKey.pollEvents();
for (WatchEvent event : events) {
if (event.kind() == ENTRY_CREATE) {
System.out.println("Create: " + event.context().toString());
getEventMap().put(event.context().toString(), event);
}
if (event.kind() == ENTRY_DELETE) {
System.out.println("Delete: " + event.context().toString());
getEventMap().put(event.context().toString(), event);
}
if (event.kind() == ENTRY_MODIFY) {
System.out.println("Modify: " + event.context().toString());
getEventMap().put(event.context().toString(), event);
}
}
watchKey.reset();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}