How to monitor file changes using java.nio JDK 7 API (WatcherService example)


If you want to monitor files under a directory, you can use the following source code.

This program will monitor files for the events such as MODIFY,CREATE and DELETE.

(Don’t forget this program requires JDK 7.0)

package watcherserviceexamplejdk7;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKind.*;

/**
*
* @author tunatore
*/
public class WatcherServiceExampleJDK7 {

public static void main(String[] args) throws IOException, InterruptedException {
monitorFilesInDirectory("C:\\directoryname");
}

public static void monitorFilesInDirectory(String directory) {

try {
//create a WatcherService object for monitoring directories
WatchService watchService = FileSystems.getDefault().newWatchService();
//getting the path object for the directory given by users
Path path = Paths.get(directory);
//register the events to be notified by the program
path.register(watchService, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
while (true) {
//infinite loop will take events
WatchKey key = watchService.take();
for (WatchEvent<?> watchEvent : key.pollEvents()) {
//getting the type of the event
WatchEvent.Kind<?> kind = watchEvent.kind();
//getting the file name from the WatchEvent object
Path file = (Path) watchEvent.context();
System.out.println("Filename --> " + file + " Event type --> " + kind.name());
}
//reset the current event and wait for other events
key.reset();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Here is an example output for the program;

processes taken in the following order

1. Created a file named abc.txt (under the directory)
2. Modified abc.txt

3. Deleted abc.txt file

Filename –> New Text Document.txt Event type –> ENTRY_CREATE
Filename –> New Text Document.txt Event type –> ENTRY_DELETE
Filename –> abc.txt Event type –> ENTRY_CREATE

Filename –> abc.txt Event type –> ENTRY_MODIFY
Filename –> abc.txt Event type –> ENTRY_MODIFY
Filename –> abc.txt Event type –> ENTRY_DELETE

BUILD STOPPED (total time: 1 minute 57 seconds)

Download Source Code

Advertisements