#JavaNextLevel

Veröffentlicht am: 18 November 2023
auf dem Kanal: Java Next Level
27
0

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. #NextLevelJava

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.


Auf dieser Seite können Sie das Online-Video #JavaNextLevel mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Java Next Level 18 November 2023 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 27 Mal angesehen und es wurde von 0 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!