javajava-7watchservice

JAVA 7 watch service


How can I have the watch service process any files that are in the directory on when the application starts up?

I already have the application running, but I noticed that only new files that are dropped in the directory are processed but files that were there from the start are ignored.


Solution

  • I have the same use case here and I am surprised that I did not find much useful online for such common scenario. I see some problems on the below approach. Let's say we utilize the walkTree method to scan the existing files in the directory and then register the directory for WatchService.

    1. Files.walkTree(...);
    2. Path dir =  Paths.get(...);
    3. WatchService watcher = dir.getFileSystem().newWatchService();       
    4. dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
    5. // other logic
    

    What about the files that are created after line 1 just finishes and before line 5 starts. I am just use this as a rough boundary to make discussions easier. The real boundary of window for opportunity to loss of files may be even broader.