I have the below code for monitoring a folder for any changes in java:
public class FolderWatcher
{
// public List events = new ArrayLis
in my case, this code was successfull:
try {
Path rootFolder = Paths.get(ctxProperties.getProperty("rootFolder"));
WatchService watcher = rootFolder.getFileSystem().newWatchService();
rootFolder.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
while (true) {
WatchKey watchKey = watcher.take();
if (watchKey != null) {
for (WatchEvent event : watchKey.pollEvents()) {
if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
String fileName = rootFolder.toString() + "/" + event.context().toString();
String messageStr = convertFileToString(fileName);
if (messageStr != null) {
try {
sendMessage(jmsPublisher, messageStr, getJmsProperties());
moveMessageToProcessedDirectory(fileName, ctxProperties.getProperty("successFolder"), ".ok");
LOGGER.info("JMS message successfully sent");
sleep(Long.parseLong(ctxProperties.getProperty("sleepBetweenMsgMse")));
} catch (Exception e) {
moveMessageToProcessedDirectory(fileName, ctxProperties.getProperty("errorFolder"), ".nok");
}
} else {
LOGGER.error("ERROR: error parsing file content to string with file: " + fileName);
moveMessageToProcessedDirectory(fileName, ctxProperties.getProperty("errorFolder"), ".nok");
}
}
}
boolean valid = watchKey.reset();
if (!valid) {
LOGGER.error("ERROR: the watcher is no longer valid, the directory is inaccessible");
break;
}
} else {
LOGGER.error("ERROR: the watcher is null or not watchable");
break;
}
}
} catch (InterruptedException interruptedException) {
LOGGER.error("InterruptedException: thread got interrupted",interruptedException);
} catch (Exception exception) {
LOGGER.error("Exception: " + exception.getMessage(), exception);
}