Class FileChangeWatcher


  • public final class FileChangeWatcher
    extends Object
    Instances of this class can be used to watch a directory for file changes. When a file is added to, deleted from, or is modified in the given directory, the callback provided by the user will be called from a background thread. Some things to keep in mind:
    • The callback should be thread-safe.
    • Changes that happen around the time the thread is started may be missed.
    • There is a delay between a file changing and the callback firing.
    • The watch is not recursive - changes to subdirectories will not trigger a callback.
    • Constructor Detail

      • FileChangeWatcher

        public FileChangeWatcher​(Path dirPath,
                                 Consumer<WatchEvent<?>> callback)
                          throws IOException
        Creates a watcher that watches dirPath and invokes callback on changes.
        Parameters:
        dirPath - the directory to watch.
        callback - the callback to invoke with events. event.kind() will return the type of event, and event.context() will return the filename relative to dirPath.
        Throws:
        IOException - if there is an error creating the WatchService.
    • Method Detail

      • start

        public void start()
        Tells the background thread to start. Does not wait for it to be running. Calling this method more than once has no effect.
      • stop

        public void stop()
        Tells the background thread to stop. Does not wait for it to exit.