The java.nio.file package provides a file change notification API, called the Watch Service API. This API enables you to register a directory (or directories) with the watch service. When registering, you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When an event comes in, it is handled as needed. #okayjava
Here are the basic steps required to implement a watch service:
1. Create a WatchService "watcher" for the file system.
2. For each directory that you want monitored, register it with the watcher.
3. When registering a directory, you specify the type of events for which you want notification. You receive a WatchKey instance for each directory that you register.
4. Implement an infinite loop to wait for incoming events. When an event occurs, the key is signaled and placed into the watcher's queue.
5. Retrieve the key from the watcher's queue. You can obtain the file name from the key.
6. Retrieve each pending event for the key (there might be multiple events) and process as needed.
7. Reset the key, and resume waiting for events.
8. Close the service: The watch service exits when either the thread exits or when it is closed (by invoking its closed method).
WatchKeys are thread-safe and can be used with the java.nio.concurrent package. You can dedicate a thread pool to this effort.
Credit docs.oracle.co...
5 сен 2024