直接上代码:
package com.dyy.spring.service;
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 FileWatchDemo {
private static String path = "D:/code_dyy/practice/files/";
public static void main(String[] args) throws IOException {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path p = Paths.get(path);
p.register(watcher,StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_CREATE);
ExecutorService fixedThreadPool = Executors.newCachedThreadPool();
fixedThreadPool.execute(new Listener(watcher));
}
}
class Listener implements Runnable {
private WatchService watcher;
public Listener(WatchService watcher) {
this.watcher = watcher;
}
public void run() {
try {
while(true){
WatchKey watchKey = watcher.take();
List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
for(WatchEvent<?> event : watchEvents){
//TODO 根据事件类型采取不同的操作。。。。。。。
if(StandardWatchEventKinds.ENTRY_MODIFY.name().equals(event.kind().name())){
System.out.println("[" + event.context() + "]文件发生了[" + event.kind() + "]事件" + event.count());
}
}
watchKey.reset();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
System.out.println("fdsfsdf");
try {
watcher.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
1294




被折叠的 条评论
为什么被折叠?



