Pages Navigation Menu

Coding is much easier than you think

Monitor a Folder using Java

Monitor a Folder using Java

 

Consider a scenario such that we have a FTP folder where in an external system will post a file and our program has to monitor that FTP folder and when a new file arrives we need to read it or email it.
 
To implement this scenario, Java version 7 provided an update for IO package. NIO package was a significant update in this version. It has got a set of interfaces and classes to help this job done.

WatchService and Watchable

WatchService and Watchable provides the framework to watch registered object for changes using Java. When we watch files and folder we need to obtain an interface to the underlying native file system. For that we can use the FileSystems class.

Example:

File : MonitorFolder

Following program, provides implementation for watching a folder for a new file. We obtain the instance of WatchService using the FileSystems class. Then the path to be watched is registered with this instance of WatchService for the CREATE event. When a new file is created we get the event with the context. In this sample, we just get the file name and print it in the console. Here we can include our business service, such as to read the file or send an email.

 

package com.simplecode.net;

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

public class MonitorFolder
{
public static void main(String[] arg) throws IOException,InterruptedException
{

Path fileFolder = Paths.get("./file/");
WatchService watchService = FileSystems.getDefault().newWatchService();
fileFolder.register(watchService, NTRY_CREATE, ENTRY_DELETE,ENTRY_MODIFY);

boolean valid = true;
do
{
	WatchKey watchKey = watchService.take();

	for (WatchEvent<?> event : watchKey.pollEvents())
	{
		if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind()))
		{
		String fileName = event.context().toString();
		System.out.println("File Created:" + fileName);
		}
	}
	valid = watchKey.reset();
} while (valid);
}
}

About Mohaideen Jamil