I have the below code for monitoring a folder for any changes in java:
public class FolderWatcher
{
// public List events = new ArrayLis
Why don't you store a metadata
file in each folder (recursively
), in that metadata
file you can store file list
and modified date
and size
of each file. Your thread should compare this metadata
file in each folder with the current files
present in the same.
That is how you can detect any change within that folder.
Remember you should do it recursively for each subfolder
within that. And the metadata
file should be updated with each scan.
Hope this helps..
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);
}