我有一个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
}
}
}
关于java - 如何在特定条件下执行java程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30586198/