I'd like to be notified when a file has been changed in the file system. I have found nothing but a thread that polls the lastModified File property and clearly this solution is not optimal.
A watch service that watches registered objects for changes and events. For example a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted.
The first step is to create a new WatchService by using the newWatchService() method of the FileSystem class. Next, we register a Path instance for the folder to be monitored with the types of events that we are interested in. And at last, we implement an infinite loop to wait for incoming events.
I've written a log file monitor before, and I found that the impact on system performance of polling the attributes of a single file, a few times a second, is actually very small.
Java 7, as part of NIO.2 has added the WatchService API
The WatchService API is designed for applications that need to be notified about file change events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With