参考的博客

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();
}
} }
}

最新文章

  1. APP性能测试之卡顿比(FPS)
  2. iOS实现书架布局样式【一些电子书的首页】
  3. 一些常用css技巧的为什么(一)我所理解的margin
  4. 【ActionScript】ActionScript3.0对舞台组件的增删改查
  5. SSD -----TLC MLC SLC
  6. Java获取.properties配置文件某一项value根据key值
  7. Python基础-修改excel、redis、接口开发、组织代码
  8. Install alipay支付宝安全控件 on firefox in linux
  9. 卸载vs2017
  10. python字典按照value进行排序.bak
  11. c# 如何调用python脚本
  12. xtrabackup备份之增量备份(二)
  13. Javascript变长参数和默认参数
  14. VS2017安装后如何移动 Windows Kits文件夹
  15. 【opencv入门篇】 10个程序快速上手opencv【上】
  16. PTA 1004 Counting Leaves (30)(30 分)(dfs或者bfs)
  17. Altium_Designer-如何放置总线
  18. Hibernate 表连接hql语句
  19. IOS 监听slider滑动
  20. JZOJ 3462. 【NOIP2013模拟联考5】休息(rest)

热门文章

  1. Dockerfile 的常用参数注解和范例
  2. Phalcon如何创建多模块并能进行访问 《Phalcon入坑指南系列 四》
  3. selenium--启动不同的浏览器
  4. 数据结构与算法——迪杰斯特拉(Dijkstra)算法
  5. java 从零开始手写 RPC (03) 如何实现客户端调用服务端?
  6. c++ fstream feekg讨论
  7. 易华录 X ShardingSphere|葫芦 App 后台数据处理的逻辑捷径
  8. Task 异步小技巧
  9. C语言的return语句
  10. C++ cin和while cin