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

时间:2019-03-07 17:14:41

标签: java watchservice

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

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);
    }
}

}

当我在受监视并保存更改的文件夹中编辑单词文件(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应用程序在此编辑过程中创建的临时文件引起的。

是否可以过滤事件以仅从单词文件(TEST.docx)中获取事件,而忽略源自临时文件的事件?

谢谢

1 个答案:

答案 0 :(得分:1)

在我的应用程序中,我只需添加一个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源代码,但与该简单解决方案相比,我看不出该解决方案有什么好处。