Java File Watcher
It is one of the less well-known features of the more recent IO APIs that were introduced with the FileVisitor interface in Java 7.
WatchService provides a platform-independent way to monitor file and directory changes using the underlying file system's native mechanisms. Java programs become capable of receiving instantaneous notifications regarding alterations made to the file system with the help of this feature.
It would help if you imported the necessary classes to utilize the WatchService interface in your applications:
The Use WatchService
The IDE serves as a popular illustration of what the service does.
You may have seen the IDEs constantly identify changes to source code files elsewhere. Although some IDEs update your file in the background, others let you reload the file from the filesystem using a dialogue box.
According to this, more recent frameworks, like Play, automatically reload the application code anytime you make changes in any editor.
All filesystems include a feature known as file change notification, which these apps use.
We may create code to check the filesystem frequently for modifications to certain files and directories. Nevertheless, this method could be more scalable, particularly if there are hundreds or thousands of files and folders.
Java 7 NIO offers a scalable method for checking folders for changes.2's WatchService API. We are not required to develop our solution because it has a clear API and is performance-tuned.
How Does the Watch service Work
Using the java.nio.file.FileSystems to create a WatchService instance is the first step in accessing the WatchService features. Class for FileSystems:
The path to the directory we want to watch must then be created:
We then need to register the path with the watch service. At this point, you need to comprehend two key ideas. the classes WatchKey and StandardWatchEventKinds. To understand where each registration code falls, look at the following. We shall next provide the following explanations:
Only two critical points should be noted here: The watch service instance is sent as the initial parameter to the route register API call, which is then proceeded by variable parameters of StandardWatchEventKinds. Next, a WatchKey instance is the result type from the registration procedure.
StandardWatchEventKinds is an enumeration in the Java NIO.2 package that defines the types of events that the WatchService can monitor. It contains the following event kinds:
The registration of such a directory with the watch service is represented by this class. Whenever we create a directory and inquire whether any of the events we registered for have occurred, the watch service returns its instance to us.
The callback methods the Watch service provides aren't invoked when an event occurs. Only by polling it in various ways can we obtain this data.
We can use the poll API to do the following:
Each API request immediately returns. Whether any events from the queued watch have happened, it delivers the next queued watch key; otherwise, it returns null.
Another variant of both the case that requires a delay is that it is overloaded:
The return value of this API call is comparable to that of the preceding one. Rather than immediately returning null, it blocks for timeout units to provide additional time for an event to occur.
Finally, we may employ the take API:
Until an event occurs, this final method will be blocked.
We must make an essential observation here: if the reset API is not used once the WatchKey object is returned by any of the polls or take APIs, it will stop capturing events:
The fact that the watch key instance was removed from the watch service queue each time a poll operation returned indicates. It is returned to the queue to watch for further events following the reset API call.
The watcher service will need to be used in a loop where we continually check for changes in the monitored directory and act accordingly. To do this, we may utilize the idiom that goes like this:
We make a watch key to store the result of both poll actions. The while loop will remain inactive unless the conditional expression returns with a watch key or null.
The while loop runs the method inside it once we get a watch key. A list of recent events is returned using WatchKey.pollEvents API. Next, we handle each one individually using a for each loop.
After all, events have been handled; we must use the reset API to re-enqueue the watch key.
In the preceding part, we have already discussed the WatchService API's internal workings and practical applications, allowing us to move on to a comprehensive and real-world example.
We will monitor activity in the user home directory, which should be accessible on all current operating systems, for portability-related reasons.
Follow the given steps below to run the program.
Step 1: First we have created filewatcerdemo folder.
Step 2: Inside the filewatcherdemo folder, go to src, create a package name "com.watcher.demo" and create a class inside that package FileWatcherService.java.
Step 3: Now, type the program in the FileWatchService.java file. Now create a new folder of your choice we have created as "watcher" and save in the system. Now copy the path of the system and paste it into the above code.
Step 4: Now copy the path of the watcher file and paste it into the above code.
Step 4: Now save the code, compile it first, and then run the program. Now open the watcher folder we created and create a new next text file in .txt format.
We can observe that the code executes the following command will execute Event type ENTRY_CREATE File affected New Text Document.txt
Step 5: If we try to delete the text file, we can observe that the following command will execute Event type ENTRY_DELETE File affected New Text Document.txt
Step 6: If we try to Modify the text file, we can observe that the following command will execute Event type ENTRY_MODIFY File affected New Text Document.txt
You can create a file or directory, modify the contents of a file, or even delete a file in the user home directory. All of these actions will be logged at the console.