#JavaNextLevel

Publicado em: 18 Novembro 2023
no canal de: 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.


Nesta página do site você pode assistir ao vídeo on-line #JavaNextLevel duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário Java Next Level 18 Novembro 2023, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 27 vezes e gostou 0 espectadores. Boa visualização!