This project allows watching files for different file events like create,modify & delete and then act on these events in generic way.
- Create a Path object representing the directory to monitor for file events.
Path path = Paths.get("/home/omkar/test");
- Implement the FileHandler interface to perform an action detected by file event registered.
public class FileHandlerTest implements FileHandler {
private static final Logger LOGGER = Logger.getLogger(FileHandlerTest.class.getName());
/*
* This implemented method will delete the file
*
* @see com.io.util.FileHandler#handle(java.io.File,
* java.nio.file.WatchEvent.Kind)
*/
public void handle(File file, Kind<?> fileEvent) {
LOGGER.log(Level.INFO,"Handler is triggered for file {0}",file.getPath());
if(fileEvent == StandardWatchEventKinds.ENTRY_CREATE) {
try {
boolean deleted = Files.deleteIfExists(Paths.get(file.getPath()));
assertTrue(deleted);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- Create an instance of an Implemented FileHandler
FileHandlerTest fileHandlerTest = new FileHandlerTest();
- Create an instance of a FileWatcher by passing path,an instance of an Implemented FileHandler and types of file events that you want to monitor separated by commas.
FileWatcher fileWatcher = new FileWatcher(path, fileHandlerTest,false, StandardWatchEventKinds.ENTRY_CREATE);
//For non-recursive polling
OR
FileWatcher fileWatcher = new FileWatcher(path, fileHandlerTest,true, StandardWatchEventKinds.ENTRY_CREATE);
//For recursive polling
- Now Create and start a new Thread.It is recommended to use ExecutorService.
Thread watcherThread = new Thread(fileWatcher);
watcherThread.start();
This thread will start polling for your registered file events and will invoke your custom handle method once any of the registered events are detected.
- Omkar Marathe - Initial work - Omkar
If you've found an error in this sample, please file an issue here
Patches are encouraged, and may be submitted by forking this project and submitting a pull request through GitHub.
This project is licensed under the Apache License - see the LICENSE file for details