
代码中的目录监听功能
5星
- 浏览量: 0
- 大小:None
- 文件类型:None
简介:
简介:本文介绍了在编程中实现目录监听功能的方法和技术,帮助开发者实时监控文件系统的变动。
Java实现实时目录监听的示例代码如下:
首先需要使用`java.nio.file.WatchService`接口来创建一个监控服务,并将要监听的目录注册到该服务中。
```java
import java.io.IOException;
import java.nio.file.*;
public class DirectoryWatcher {
private static void registerDirectory(Path dir, WatchService wservice) throws IOException {
// Register the directory with the watch service for ENTRY_CREATE events.
dir.register(wservice, StandardWatchEventKinds.ENTRY_CREATE);
}
public static void main(String[] args) {
try (WatchService wservice = FileSystems.getDefault().newWatchService()) {
Path path = Paths.get(/path/to/directory);
registerDirectory(path, wservice);
while(true){
WatchKey key;
try {
key = wservice.take();
} catch (InterruptedException ex) {
return;
}
for (WatchEvent> event : key.pollEvents()) {
Path filename = ((WatchEvent
全部评论 (0)


