多次触发WatchService(触发MODIFY,甚至在创建完成之前)JAVA
我有一个服务可以检查文件夹中的ZIP文件多次触发WatchService(触发MODIFY,甚至在创建完成之前)JAVA,java,watchservice,Java,Watchservice,我有一个服务可以检查文件夹中的ZIP文件 while(true) { WatchKey wk = watchService.take(); for (WatchEvent<?> event : wk.pollEvents()) { Kind<?> eventKind = event.kind(); Path dir = (Path)wk.watchable(); Pat
while(true) {
WatchKey wk = watchService.take();
for (WatchEvent<?> event : wk.pollEvents()) {
Kind<?> eventKind = event.kind();
Path dir = (Path)wk.watchable();
Path eventPath = (Path) event.context();
Path fullPath = dir.resolve(eventPath);
fireAction(eventKind, fullPath);
}
wk.reset();
}
while(true){
WatchKey wk=watchService.take();
for(WatchEvent事件:wk.pollEvents()){
种类eventKind=event.Kind();
Path dir=(Path)wk.watchable();
Path eventPath=(Path)event.context();
Path fullPath=dir.resolve(eventPath);
fireAction(eventKind、fullPath);
}
wk.reset();
}
在这里,如果您看到,每次执行操作时,调用fireAction()方法,下面是方法
public void fireAction(Kind<?> eventKind, Path eventPath) {
synchronized (listeners) {
if (eventKind == StandardWatchEventKinds.ENTRY_MODIFY) {
fileModified(this, eventPath);
} else if (eventKind == StandardWatchEventKinds.ENTRY_DELETE) {
fileDeleted(this, eventPath);
} else if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) {
fileCreated(this, eventPath);
}
}
}
public void fireAction(种类eventKind,路径eventPath){
已同步(侦听器){
if(eventKind==StandardWatchEventKinds.ENTRY\u MODIFY){
fileModified(这是eventPath);
}else if(eventKind==StandardWatchEventKinds.ENTRY\u DELETE){
已删除文件(此,事件路径);
}else if(eventKind==StandardWatchEventKinds.ENTRY\u CREATE){
创建的文件(此,事件路径);
}
}
}
因此,当文件夹为空并且我第一次将ZIP保存在文件夹中时,会调用fileCreate()方法,但不会完成,fileModify()方法会被触发,fileModify()会被触发两次。当我从文件夹中删除ZIP时,它工作正常,但当我再次保留ZIP时,它工作正常
因此,只有当问题第一次出现时。请给我任何建议,这是我尝试过的
为正在创建的文件生成校验和,并将校验和存储在值中,并将键设置为映射中文件的路径,当触发modify时,只需验证校验和和文件 如果存在校验和,请不要修改,否则请修改 应该很容易实现,我也这么做了