Java应用中实时坚控文件变化是常见需求,本文详细讲解如何基于WatchService封装高效可靠的目录器,并实现业务解耦的热更新方案。
在实际开发中,配置文件热加载、插件更新等场景都需要对文件系统变化做出实时响应。Java NIO提供的WatchService正是解决这类问题的利器。

本文将系统介绍:
public class DirectoryWatcher implements Runnable {
private final Path watchDir;
private final WatchService watchService;
private final FileChangeHandler handler;
public DirectoryWatcher(Path dir, FileChangeHandler handler) throws IOException {
this.watchDir = dir;
this.handler = handler;
this.watchService = FileSystems.getDefault().newWatchService();
register();
}
private void register() throws IOException {
watchDir.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
}
@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
WatchKey key = watchService.take();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
Path filename = (Path) event.context();
Path fullPath = watchDir.resolve(filename);
handler.onFileChanged(fullPath, kind);
}
key.reset();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
e.printStackTrace();
} finally {
try { watchService.close(); } catch (IOException ignored) {}
}
}
public interface FileChangeHandler {
void onFileChanged(Path path, WatchEvent.Kind<?> kind);
}
}核心特性:
以JSON配置文件热加载为例:
public class ConfigLoader {
public void load(Path file) {
// 读取并解析 JSON 文件,更新内存配置
System.out.println("配置文件更新:" + file.getFileName());
}
}
public class ConfigHotReload {
public static void main(String[] args) throws Exception {
Path configDir = Paths.get("config");
ConfigLoader loader = new ConfigLoader();
DirectoryWatcher watcher = new DirectoryWatcher(configDir, (path, kind) -> {
if (path.toString().endsWith(".json")) {
loader.load(path);
}
});
Thread thread = new Thread(watcher, "ConfigHotReload");
thread.setDaemon(true);
thread.start();
// 主线程继续其他工作
Thread.sleep(Long.MAX_VALUE);
}
}实现要点:
本文方案通过WatchService封装实现了高可用的文件框架,具有职责分离、便于复用和灵活扩展三大优势,可有效提升配置管理、插件系统等场景的开发效率和系统稳定性。