Java WatchService API事件,更改可编辑文件(word、odt等)
我正在使用以下代码来驱动文件夹,以获取创建、修改和删除文件的事件Java WatchService API事件,更改可编辑文件(word、odt等),java,watchservice,Java,Watchservice,我正在使用以下代码来驱动文件夹,以获取创建、修改和删除文件的事件 public static void main(String[] args){ try { Path dir = Paths.get("D:/Temp/"); WatchService watcher = FileSystems.getDefault().newWatchService(); dir.register(watcher, StandardWatchEve
public static void main(String[] args){
try {
Path dir = Paths.get("D:/Temp/");
WatchService watcher = FileSystems.getDefault().newWatchService();
dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watcher.take())!=null){
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
@SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();
if(kind==StandardWatchEventKinds.ENTRY_CREATE){
System.out.println("New File Added, file Name " + fileName);
}
if(kind==StandardWatchEventKinds.ENTRY_DELETE){
System.out.println("File Deleted " + fileName);
}
if (kind == StandardWatchEventKinds.ENTRY_MODIFY ){
System.out.println("File Modified " + fileName);
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
} catch (IOException ex) {
System.err.println(ex);
}
}
某些事件是由Word应用程序在此编辑过程中创建的临时文件引起的
是否有任何方法可以过滤事件,只从word文件(TEST.docx
)中获取事件,而忽略来自临时文件的事件
谢谢在我的应用程序中,我只需添加一个if条件即可过滤掉它们:
...
final Path changed = (Path) event.context();
WatchEvent.Kind<?> kind = event.kind();
if (changed.toString().startsWith("TEST.docx")) {
if(kind==StandardWatchEventKinds.ENTRY_CREATE){
System.out.println("New File Added, file Name " + fileName);
}
}
。。。
最终路径已更改=(路径)event.context();
WatchEvent.Kind-Kind=event.Kind();
if(changed.toString().startsWith(“TEST.docx”)){
if(kind==StandardWatchEventKinds.ENTRY\u CREATE){
System.out.println(“添加新文件,文件名”+文件名);
}
}
据我所知,WatchService监视文件夹中所有文件中的所有已注册事件(在您的情况下为ENTRY\u CREATE、ENTRY\u MODIFY、ENTRY\u DELETE)。另一种方法是分叉WatchService源代码,但我不知道该解决方案与这个简单的解决方案相比有什么好处。Veli Matti Sorvala。谢谢你的回答。这是一个有效的解决方案
...
final Path changed = (Path) event.context();
WatchEvent.Kind<?> kind = event.kind();
if (changed.toString().startsWith("TEST.docx")) {
if(kind==StandardWatchEventKinds.ENTRY_CREATE){
System.out.println("New File Added, file Name " + fileName);
}
}