`
HongCheng
  • 浏览: 26039 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

NIO2.0文件监听

    博客分类:
  • JDK7
阅读更多
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

/*
* 文件监听
*
* 实现流程如下:
*
*1.为文件系统创建一个WatchService 实例 watcher
*2.为你想监听的目录注册 watcher。注册时,要注明监听那些事件。
*3.在无限循环里面等待事件的触发。当一个事件发生时,key发出信号,并且加入到watcher的queue
* 4.从watcher的queue查找到key,你可以从中获取到文件名等相关信息
* 5.遍历key的各种事件
* 6.重置 key,重新等待事件
* 7.关闭服务
*/
public class TestIOWatchDir {
public void watchDir(String dirPath) {
try {
Path path = Paths.get(dirPath);
WatchService watcher = FileSystems.getDefault().newWatchService();
// path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
path.register(watcher, ENTRY_CREATE);
while (true) {
WatchKey key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
continue;
}
Path filePath = (Path) event.context();
System.out.println(filePath);
key.reset();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
String dirPath = "D:/";
new TestIOWatchDir().watchDir(dirPath);
}

}

备注:参考的相关资源来源于网络ITEYE
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics