实现代码如下:
import java.nio.file.*;
public class Test {
public static void main(String[] args) throws Exception {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get("D:\\watchservice\\");
path.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY
);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.err.println("事件:" + event.kind() + ",发生了变化,文件是:" + event.context());
}
key.reset();
}
}
}
WatchService接口是在java7的版本中引入的。主要是处理NIO的文件相关问题。但是WatchService其实是有很多缺点的。
- WatchService是采用扫描式的,效率低。
- WatchService代码写起来费劲。虽然下面看起来很简洁了,但是实际开发时麻烦。
- WatchService不能监听到多级目录,事先父文件夹需要存在。
鉴于以上原因,在简单的实现时,可以使用。
参考:java监听文件变化