WatchService API 事件,更改可编辑文件(word、odt、....)

WatchService API events, change editable files (word, odt,....)

我正在使用以下代码来驱动文件夹,以获取文件的创建、修改和删除事件

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文件(TEST.docx)时,显示以下事件结果:

New File Added, file Name ~$TEST.docx
File Modified ~$TEST.docx
New File Added, file Name ~WRD0000.tmp
File Modified ~WRD0000.tmp
File Deleted TEST.docx
New File Added, file Name ~WRL0001.tmp
File Deleted ~WRD0000.tmp
New File Added, file Name TEST.docx
File Modified TEST.docx
File Modified ~WRL0001.tmp
New File Added, file Name ~WRD0002.tmp
File Modified ~WRD0002.tmp
File Deleted TEST.docx
New File Added, file Name ~WRL0003.tmp
File Deleted ~WRD0002.tmp
New File Added, file Name TEST.docx
File Modified TEST.docx
File Modified ~WRL0003.tmp
File Deleted ~WRL0003.tmp
File Deleted ~WRL0001.tmp
File Deleted ~$TEST.docx

一些事件是由 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);
            }

}

据我所知,WatchService 监视所有已注册的事件(在您的情况下 ENTRY_CREATE、ENTRY_MODIFY、ENTRY_DELETE)在所有文件中在文件夹中。另一种方法是分叉 WatchService 源,但我看不出该解决方案与这个简单的解决方案相比有什么好处。