[英]Watching a Directory for Changes Java.nio.file
我知道java.nio.file
可以提供监视文件更改的方法,例如新文件,修改和删除。 但是现在我想知道是否有一种方法可以查看是否由某些应用程序(例如编辑器)输入了目录或正在打开一个文件。
我已经阅读了API文档,无法找到实现此目的的方法。 任何人都可以提供有关此方面的线索,也许是其他API文档,而不是java.nio.file
可以提供解决此问题的方法。
查看http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html
至于您可以观看的内容,请查看http://docs.oracle.com/javase/7/docs/api/java/nio/file/StandardWatchEventKinds.html
它似乎不支持您在其他注释中指示的诸如“正在打开文件”或“有人进入目录”之类的内容。
这是一个简单观察者的示例:
package com.stackoverflow.answers;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class FolderWatcher {
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = FileSystems.getDefault().getPath("c:/Temp");
dir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
// ...
for (;;) {
WatchKey key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("Got event: " + event.kind());
if (event.kind() == StandardWatchEventKinds.OVERFLOW) continue;
System.out.println("File: " + ((WatchEvent<Path>)event).context());
}
}
}
}
有关更完整的处理,请查看本教程: http : //docs.oracle.com/javase/tutorial/essential/io/notification.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.