2

I have a java program and I want to have it spy on some folders and once the folder has some new pdf files, I want to do some tasks on the new pdfs.

And I also want to avoid restarting java program (the task with pdf part) every time when new files come in because the initialization takes a long time. How can I realize it?

1a1a11a
  • 1,187
  • 2
  • 16
  • 25
  • You need File Change Listener. [Here][1] is good example. [1]: http://stackoverflow.com/questions/494869/file-changed-listener-in-java – Alex Jun 02 '15 at 02:16

1 Answers1

2

Check out WatchService (Great example and explanation here) https://docs.oracle.com/javase/tutorial/essential/io/notification.html

        // Adding directory listener
        WatchService watcher = FileSystems.getDefault().newWatchService();
        Path tempPath = Paths.get("C:\\xampp\\htdocs\\someDirectory");
        tempPath.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY);


while (true) {
                WatchKey key = watcher.take();

                // Poll all the events queued for the key.
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind kind = event.kind();
                    if (kind.name().endsWith("ENTRY_CREATE")) {
                        // Do something  
                    }
                }
}
Jurko Guba
  • 630
  • 7
  • 17