在Java 7发布的新的IO框架中,除了大家都熟知的 FileVisitor 接口外,还有个 WatchService 接口经常被人忽视掉。 这个类可以让你实时的监控操作系统中文件的变化,包括创建、更新和删除事件。
WatchService 用来观察被注册了的对象的变化和事件。它和Watchable两个接口的配合使用, WatchService类似于在观察者模式中的观察者,Watchable类似域观察者模式中的被观察者。
而Java 7中的java.nio.file.Path类就实现了Watchable接口,这样的话,和Path类一起可实现观察者模式。
package com.huawei.leetcode;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;
/**
* TODO Class Description
* @since 2019-11-20
*/
public class DirectoryWatcherExample {
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
//需要监听的文件目录(只能监听目录)
Path path = Paths.get("D:\\code\\my_exercise_code\\src\\com\\xx\\leetcode");
path.register(watchService,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_CREATE);
Thread thread = new Thread(() -> {
try {
while (true) {
WatchKey watchKey = watchService.take();
List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
for (WatchEvent<?> event : watchEvents) {
Path fileName = (Path) event.context();
System.out.println("文件更新: " + fileName);
System.out.println("FileName: " + fileName.getFileName());
if (event.context().toString().contains("xx.txt")) {
System.out.println(event.context() + "]文件发生了[" + event.kind() + "]事件");
}
}
watchKey.reset();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
System.out.println("-------success-------");
}
}
参考文献:使用WatchService监听文件变化