Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File changed listener in Java

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.

like image 564
cheng81 Avatar asked Jan 30 '09 08:01

cheng81


People also ask

What is Java WatchService?

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.

How do you use standard Java libraries to make a file watcher?

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.


1 Answers

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.

like image 67
Stephen Denne Avatar answered Sep 27 '22 21:09

Stephen Denne