6.6. Watch a directory for changes by using WatchService - Source Code

Code:


package c6.s6;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

/**
 * @author Mikalai Zaikin
 */
public class WatchServiceExample {

    public static void main(String... args) throws IOException, InterruptedException {
        Path watchDir = Paths.get("C:\\home");

        WatchService watchService = FileSystems.getDefault().newWatchService();

        WatchKey watchKey = watchDir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);

        // Create a file inside our watched directory
        File newFile = new File(watchDir.toFile(), "newFile.txt");
        newFile.createNewFile();

        for (;;) {
            // Call take() and see if the event has been registered
            WatchKey key = watchService.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                System.out.print(String.format("An event was found of kind %s.%n", event.kind()));
                System.out.print(String.format("The event occurred on file '%s'.%n", event.context()));
            }

            // Reset the key - this step is critical if you want to receive further watch events !!!
            key.reset();
        }
    }
}

					

output:

An event was found of kind ENTRY_CREATE.
The event occurred on file 'newFile.txt'.
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide