从 Java 1.7 开始,有一种方法可以在不添加额外库的情况下查看目录。在 Oracle 网站上,有一个小教程如何使用 WatchService http://docs.oracle.com/javase/tutorial/essential/io/notification.html#try,但我很难理解。没有consitent示例如何使用它。
因此,有人会告诉我如何将侦听器添加到目录并调用方法,例如:f()
当文件添加到目录时让我们说:“./folder”?
从 Java 1.7 开始,有一种方法可以在不添加额外库的情况下查看目录。在 Oracle 网站上,有一个小教程如何使用 WatchService http://docs.oracle.com/javase/tutorial/essential/io/notification.html#try,但我很难理解。没有consitent示例如何使用它。
因此,有人会告诉我如何将侦听器添加到目录并调用方法,例如:f()
当文件添加到目录时让我们说:“./folder”?
每次您在监视文件夹中创建文件时,都会调用这段代码:
Path path = new File("./folder").toPath();
WatchService watchService = FileSystems.getDefault().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
for (;;) {
try {
WatchKey key = watchService.take();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE)) {
System.out.println("file created");
}
}
} catch (InterruptedException x) {
return;
}
}