Java WatchService Sample Code

As a Java developer, I like to know when something changes with the configuration file, for example, that my Java application read at startup. Now what happens if you modify a parameter in the config file after startup? Nothing unless you are watching for changes.

Thankfully Java has the WatchService class that will watch for changes (change | add | delete) of files in a specific directory. The sample java code below is pretty simple, but is a good example of how to implement the Java WatchService.

The sample Java WatchService class file is the main file that starts the JavaWatchServiceRunnable class file. The runnable will continually run and look for events that happen.

Java WatchService Main Source Code (Main Class):

package com.jcd.java.tutorials;


import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchService;


public class JavaWatchService 
{

	public static void main(String[] args) 
	{
		String configDirectoryToWatch = "C:\\Users\\Admin\\Documents\\conf";
		
		Path toWatch = Paths.get(configDirectoryToWatch);
		
		try 
		{
			System.out.println("Starting My Watch Service!");
			
			WatchService watchService = toWatch.getFileSystem().newWatchService();
			
			JavaWatchServiceRunnable javaWatchSvcRunnable = new JavaWatchServiceRunnable(watchService);
	        Thread th = new Thread(javaWatchSvcRunnable, "JavaWatchServiceRunnable");
	        th.start();
		
			//Register to watch for created, deleted, and modified events
			toWatch.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, 
										   StandardWatchEventKinds.ENTRY_CREATE,
										   StandardWatchEventKinds.ENTRY_DELETE);
	
		}
		catch(Exception ex) 
		{ 
			System.out.println("Exception:"+ex.toString());
		}

	}
	
}


Java WatchService Runnable Source Code (Runnable Class):

This sample code will watch for the events that we specified above. Remember that watchEvent.context() will give you the name of the file that an event (modify,create,delete) happened to. You can setup different some tasks that do different chores based on the file that is affected.

package com.jcd.java.tutorials;


import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;


public class JavaWatchServiceRunnable implements Runnable
{

	WatchService watchService;
	
	public JavaWatchServiceRunnable (WatchService myWatchService) 
	{
		watchService = myWatchService;
	}
	
	@Override
	public void run() 
	{
		try 
		{         
			
			System.out.println("\nMy Runnable Waiting on Events!\n");
			
			WatchKey key = watchService.take();
			
			while(key != null) {

                for (WatchEvent watchEvent : key.pollEvents())
                {   	
                	Kind<?> kind = watchEvent.kind();
                	
                	System.out.println("New Event: "+watchEvent.context() + " --> " + kind.toString());
                }
                
                //Make sure to reset the event that just happened
                key.reset();
                key = watchService.take();
			}
			
		} catch (Exception ex) 
		{
			System.out.println("Exception:"+ex.toString());
		}
	}
		
}


Sample Java WatchService Output:

Starting My Watch Service!

My Runnable Waiting on Events!

New Event: demo.cfg --> ENTRY_CREATE
New Event: sample.cfg --> ENTRY_MODIFY
New Event: demo.cfg --> ENTRY_DELETE



Java References:

Add a Comment

Your email address will not be published. Required fields are marked *