I want to continuously monitor a folder (say C:/Users/me/rootFolder) for any change in its content -
- New files added,
- Sub-folder changes
- Existing file modified
I have used watch services from java.nio package and am able to obtain result for the root folder. But how can we use watch services for the whole directory tree?
Also, I am searching a way to do this operation using timestamp instead of watchservice as it is the clients requirement.
Here is the code which I have written for root directory.
public void watchServices() throws IOException,
InterruptedException
{
destFolder = LoginController.destFolder;
logger.info("Started Watching Folder");
Path watchFolder = Paths.get(sourceFolder);
WatchService watchService = FileSystems.getDefault().newWatchService();
watchFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
boolean valid = true;
do {
WatchKey watchKey = watchService.take();
for (WatchEvent event : watchKey.pollEvents()) {
WatchEvent.Kind kind = event.kind();
if (StandardWatchEventKinds.ENTRY_CREATE.equals(kind))
{
String fileName = event.context().toString();
File file = new File(watchFolder + "\\" + fileName);
if (file.isFile())
{
logger.info("uploading file to cdi-dms server: " +
file.getAbsolutePath());
uploadFile(file,destFolder);
}
else if(file.isDirectory())
{
logger.info("creating directory in cdi-dms server: "
+ file.getAbsolutePath());
createDirectory(file,destFolder);
destFolder = destFolder+file.getName()+"/";
sync(file);
}
}
}
valid = watchKey.reset();
}while (valid);
}