390. Java IO API - WatchDir 示例
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.LinkOption.*;
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;
/**
* Example to watch a directory (or tree) for changes to files.
*/
public class WatchDir {
private final WatchService watcher;
private final Map<WatchKey,Path> keys;
private final boolean recursive;
private boolean trace = false;
@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>)event;
}
/**
* Register the given directory with the WatchService
*/
private void register(Path dir) throws IOException {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
if (trace) {
Path prev = keys.get(key);
if (prev == null) {
System.out.format("register: %s\n", dir);
} else {
if (!dir.equals(prev)) {
System.out.format("update: %s -> %s\n", prev, dir);
}
}
}
keys.put(key, dir);
}
/**
* Register the given directory, and all its sub-directories, with the
* WatchService.
*/
private void registerAll(final Path start) throws IOException {
// register directory and sub-directories
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException
{
register(dir);
return FileVisitResult.CONTINUE;
}
});
}
/**
* Creates a WatchService and registers the given directory
*/
WatchDir(Path dir, boolean recursive) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<WatchKey,Path>();
this.recursive = recursive;
if (recursive) {
System.out.format("Scanning %s ...\n", dir);
registerAll(dir);
System.out.println("Done.");
} else {
register(dir);
}
// enable trace after initial registration
this.trace = true;
}
/**
* Process all events for keys queued to the watcher
*/
void processEvents() {
for (;;) {
// wait for key to be signalled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
Path dir = keys.get(key);
if (dir == null) {
System.err.println("WatchKey not recognized!!");
continue;
}
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
// TBD - provide example of how OVERFLOW event is handled
if (kind == OVERFLOW) {
continue;
}
// Context for directory entry event is the file name of entry
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
// print out event
System.out.format("%s: %s\n", event.kind().name(), child);
// if directory is created, and watching recursively, then
// register it and its sub-directories
if (recursive && (kind == ENTRY_CREATE)) {
try {
if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) {
registerAll(child);
}
} catch (IOException x) {
// ignore to keep sample readbale
}
}
}
// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid) {
keys.remove(key);
// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
}
static void usage() {
System.err.println("usage: java WatchDir [-r] dir");
System.exit(-1);
}
public static void main(String[] args) throws IOException {
// parse arguments
if (args.length == 0 || args.length > 2)
usage();
boolean recursive = false;
int dirArg = 0;
if (args[0].equals("-r")) {
if (args.length < 2)
usage();
recursive = true;
dirArg++;
}
// register directory and process its events
Path dir = Paths.get(args[dirArg]);
new WatchDir(dir, recursive).processEvents();
}
}
WatchDir 示例:目录文件变化监控器
类概述
WatchDir 是一个用于监控目录(及其子目录)中文件变化的示例程序。它利用 WatchService API 来检测目录下文件的创建、删除和修改等事件,并提供了递归监控目录功能。通过这个示例,你可以理解如何使用 Java NIO 提供的文件监控服务来实现文件系统的变化监听。
核心功能
- 监控指定目录及其子目录:可以选择是否递归监控子目录。
- 支持的事件类型:文件的创建、删除、修改。
- 使用
WatchService接口:通过创建WatchService对象来实现事件监控。
代码结构
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.LinkOption.*;
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;
关键代码解释
1. 类成员变量
watcher:WatchService实例,用于接收和处理文件系统的变化事件。keys: 一个Map,保存了WatchKey和对应的Path,用于管理监控的目录。recursive: 标志是否需要递归监控子目录。trace: 用于打印目录变化的调试信息,帮助我们更好地了解事件发生过程。
2. cast 方法:类型转换
由于 WatchEvent 对象的泛型是未知的,cast 方法用于安全地将 WatchEvent<?> 转换为 WatchEvent<Path> 类型。并且通过 @SuppressWarnings("unchecked") 注解来消除警告。
@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>) event;
}
3. 注册目录
register 方法将指定的目录与 WatchService 注册,并指定监听的事件类型(如文件创建、删除和修改)。如果启用了 trace,程序会在控制台打印出目录的注册或更新信息。
private void register(Path dir) throws IOException {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
if (trace) {
Path prev = keys.get(key);
if (prev == null) {
System.out.format("register: %s\n", dir);
} else {
if (!dir.equals(prev)) {
System.out.format("update: %s -> %s\n", prev, dir);
}
}
}
keys.put(key, dir);
}
4. 注册所有子目录
registerAll 方法通过 Files.walkFileTree 遍历指定目录及其所有子目录,递归注册每一个目录。这使得我们可以监控整个目录树中的文件变化。
private void registerAll(final Path start) throws IOException {
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
register(dir);
return FileVisitResult.CONTINUE;
}
});
}
5. 事件处理
processEvents 方法是一个无限循环,用来处理监控到的所有事件。它会在 watcher.take() 阻塞并等待新事件的发生。每当收到事件后,程序会判断事件的类型(例如文件创建、删除或修改),并执行相应操作。
- 事件类型判断:如果事件是
OVERFLOW(事件丢失),则跳过该事件。 - 子目录注册:如果在递归监控模式下,检测到创建了新目录时,程序会自动将该目录及其子目录注册到监控队列中。
void processEvents() {
for (;;) {
WatchKey key;
try {
key = watcher.take(); // 阻塞,直到有事件到达
} catch (InterruptedException x) {
return; // 如果线程被中断,退出
}
Path dir = keys.get(key);
if (dir == null) {
System.err.println("WatchKey not recognized!!");
continue;
}
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
if (kind == OVERFLOW) {
continue;
}
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
System.out.format("%s: %s\n", event.kind().name(), child);
// 递归监控新创建的目录
if (recursive && (kind == ENTRY_CREATE)) {
try {
if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) {
registerAll(child);
}
} catch (IOException x) {
// 忽略异常以保持示例简洁
}
}
}
boolean valid = key.reset();
if (!valid) {
keys.remove(key);
if (keys.isEmpty()) {
break; // 如果没有有效的 WatchKey,退出循环
}
}
}
}
6. 主方法和参数解析
主方法首先解析命令行参数,判断是否启用递归监控(通过 -r 参数)。然后,根据参数创建 WatchDir 实例并调用 processEvents 方法开始监控。
public static void main(String[] args) throws IOException {
if (args.length == 0 || args.length > 2)
usage();
boolean recursive = false;
int dirArg = 0;
if (args[0].equals("-r")) {
if (args.length < 2)
usage();
recursive = true;
dirArg++;
}
Path dir = Paths.get(args[dirArg]);
new WatchDir(dir, recursive).processEvents();
}
7. 使用说明
usage 方法简单输出程序的用法说明,帮助用户正确传递参数。
static void usage() {
System.err.println("usage: java WatchDir [-r] dir");
System.exit(-1);
}
总结
WatchDir 示例展示了如何使用 WatchService API 来监控文件系统的变化。它能够监控指定目录(以及递归监控其子目录)的文件创建、修改和删除事件。通过注册 WatchService,我们可以实时接收到文件系统事件,并通过适当的回调处理这些事件。此外,示例还展示了如何处理递归目录监控以及如何通过类型转换来处理文件事件。
扩展和应用场景
- 日志文件监控:可以将
WatchDir程序扩展为实时监控日志文件夹,触发特定的日志处理操作(如发送通知)。 - 自动部署:应用服务器可以使用这个示例来监控部署目录,自动部署新的
.jar或.war文件。
这个示例为基于事件驱动的文件监控提供了一个简单、清晰的实现框架。