nio实现文件夹内容的监听
2024-09-08 11:14:02
参考的博客
package com.jp.filemonitor; 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;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class ResourceListener {
private static ExecutorService fixedThreadPool = Executors.newCachedThreadPool();
private WatchService ws;
private String listenerPath;
private ResourceListener(String path) {
try {
ws = FileSystems.getDefault().newWatchService();
this.listenerPath = path;
start();
} catch (IOException e) {
e.printStackTrace();
}
} private void start() {
fixedThreadPool.execute(new Listner(ws,this.listenerPath));
} public static void addListener(String path) throws IOException {
ResourceListener resourceListener = new ResourceListener(path);
Path p = Paths.get(path);
p.register(resourceListener.ws,StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_CREATE);
} public static void main(String[] args) throws IOException {
ResourceListener.addListener("F:\\");
ResourceListener.addListener("d:\\");
}
} class Listner implements Runnable {
private WatchService service;
private String rootPath; public Listner(WatchService service,String rootPath) {
this.service = service;
this.rootPath = rootPath;
} public void run() {
try {
while(true){
WatchKey watchKey = service.take();
List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
for(WatchEvent<?> event : watchEvents){ //TODO 根据事件类型采取不同的操作。。。。。。。
System.out.println("["+rootPath+event.context()+"]文件发生了["+event.kind()+"]事件"+ event.count());
}
watchKey.reset();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
System.out.println("fdsfsdf");
try {
service.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
}
最新文章
- APP性能测试之卡顿比(FPS)
- iOS实现书架布局样式【一些电子书的首页】
- 一些常用css技巧的为什么(一)我所理解的margin
- 【ActionScript】ActionScript3.0对舞台组件的增删改查
- SSD -----TLC MLC SLC
- Java获取.properties配置文件某一项value根据key值
- Python基础-修改excel、redis、接口开发、组织代码
- Install alipay支付宝安全控件 on firefox in linux
- 卸载vs2017
- python字典按照value进行排序.bak
- c# 如何调用python脚本
- xtrabackup备份之增量备份(二)
- Javascript变长参数和默认参数
- VS2017安装后如何移动 Windows Kits文件夹
- 【opencv入门篇】 10个程序快速上手opencv【上】
- PTA 1004 Counting Leaves (30)(30 分)(dfs或者bfs)
- Altium_Designer-如何放置总线
- Hibernate 表连接hql语句
- IOS 监听slider滑动
- JZOJ 3462. 【NOIP2013模拟联考5】休息(rest)