How to monitor a folder for changes in java?

后端 未结 2 1797
逝去的感伤
逝去的感伤 2021-02-09 04:19

I have the below code for monitoring a folder for any changes in java:

    public class FolderWatcher
    {
    // public List events = new ArrayLis         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-09 05:27

    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);
    }
    

提交回复
热议问题