Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        4年前关闭。
                                                                                            
                
        
我有一个Java程序,我想让它监视某些文件夹,并且一旦该文件夹包含一些新的pdf文件,我想在新的pdf上执行一些任务。

而且我还想避免每次进入新文件时都要重新启动Java程序(带有pdf部分的任务),因为初始化需要很长时间。我怎么知道呢?

最佳答案

查看WatchService(此处提供出色的示例和说明)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
                    }
                }
}

09-30 18:52