Watching a File Change

We know how to look for files and directories, but if we want to sit back and get alerts when a file is created, modified, or deleted, that’s quite easy as well. Such a facility is useful for monitoring changes to special files like configuration files and system resources. Here we’ll explore the facility that’s been available since Java 7, the WatchService, to watch for file changes. Most of the features we’ll see here are from JDK 7 and the main improvement will be in the convenience of the internal iterator.

Let’s create an example to watch for file changes in the current directory. The Path class in the JDK can lead to an instance of the file system, which acts as a factory for the watch service. We can register with ...

Get Functional Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.