Log in
updated 11:29 AM UTC, May 4, 2016

Java NIO file Watcher service example

  • Written by Madhu V Rao
  • Published in Core Java

Here is a small example to listen to the folder changes of a filesystem and notify the change to the user.

 

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

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;
import java.util.List;

import au.gov.ehp.common.Config;
import au.gov.ehp.common.Proda.CreateFileThread;

public class FolderNotification {

	public void waitTillFile() throws IOException,
			InterruptedException, Exception {

		Thread createFileThread = new Thread(new CreateFileThread());
		createFileThread.start();

		Path path = Paths.get("C:\\dev\\git\\automation\\");

		WatchService watchService = FileSystems.getDefault().newWatchService();
		WatchKey watchKey = path.register(watchService, ENTRY_CREATE,
				ENTRY_DELETE, ENTRY_MODIFY);
		WatchKey key;
		System.out.println("Now Waiting for the changes in the folder: " + path.getFileName());
		key = watchService.take();
		List<WatchEvent<?>> events = key.pollEvents();

		for (WatchEvent event : events) {
			if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
				System.out.println("Created: " + event.context().toString());
				break;
			} else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
				System.out.println("Delete: " + event.context().toString());
				break;
			} else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
				System.out.println("Modify: " + event.context().toString());
				break;
			} else {
				System.out.println("Some other type "
						+ event.context().toString());
				break;
			}
		}
		key.reset();
		watchService.close();
		System.out.println("done. Exiting the service");
	}
	
	public static void main(String args[]) throws IOException, InterruptedException, Exception {
		new FolderNotification().waitTillFile();
		System.exit(0);
	}

}

 

Here is the output:

Now Waiting for the changes in the folder: automation

Now create a folder or delete an existing folder or modify the folder.

Delete: New folder
done. Exiting the service

Powered by Bullraider.com
Follow Us on Twitter
Find Us on Facebook
Follow Us on Google
Follow Us on Pinterest