Watching a Directory for Changes in Java

前端 未结 6 487
灰色年华
灰色年华 2020-11-29 03:01

I want to watch a directory for file changes. And I used WatchService in java.nio. I can successfully listen for file created event. But I can\'t listen for file modify even

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 03:33

    Warning! Shameless self promotion!

    I have created a wrapper around Java 1.7's WatchService that allows registering a directory and any number of glob patterns. This class will take care of the filtering and only emit events you are interested in.

    DirectoryWatchService watchService = new SimpleDirectoryWatchService(); // May throw
    watchService.register( // May throw
            new DirectoryWatchService.OnFileChangeListener() {
                @Override
                public void onFileCreate(String filePath) {
                    // File created
                }
    
                @Override
                public void onFileModify(String filePath) {
                    // File modified
                }
    
                @Override
                public void onFileDelete(String filePath) {
                    // File deleted
                }
            },
            , // Directory to watch
            , // E.g. "*.log"
            , // E.g. "input-?.txt"
            ... // As many patterns as you like
    );
    
    watchService.start();
    

    Complete code is in this repo.

提交回复
热议问题