File changed listener in Java

cheng81 picture cheng81 · Jan 30, 2009 · Viewed 125.6k times · Source

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.

Answer

Stephen Denne picture Stephen Denne · Jan 30, 2009

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.