1.定义文件监听器类FsWatcher,并采用线程池实现文件里的操作队列
import com.study.aes.service.ObserverService;
import com.study.aes.service.impl.SimpleObserver;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by zem on 04/02/16.
*/
public class FsWatcher extends Thread {
private static ExecutorService fixedThreadPool = Executors.newCachedThreadPool();
private WatchService watcher;
private List<ObserverService> observers;
private ConcurrentHashMap<WatchKey, Path> keys;
public FsWatcher(Path path) throws IOException {
watcher = FileSystems.getDefault().newWatchService();
observers = new ArrayList<ObserverService>();
keys = new ConcurrentHashMap<WatchKey, Path>();
registerAll(path);
}
public void addObserver(ObserverService observer) {
observers.add(observer);
}
public void clearObservers() {
observers.clear();
}
public void register(Path path) throws IOException {
WatchKey key = path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE);
keys.put(key, path);
}
@Override
public void run() {
fixedThreadPool.execute(new Listner(watcher));
}
/**
* 监控的文件夹注册事件
*/
public void registerAll(final Path path) throws IOException {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
register(dir);
return FileVisitResult.CONTINUE;
}
});
}
private void notifyObservers(WatchEvent<Path> event, Path path) {
for (ObserverService observer : observers) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
if (Files.isDirectory(path)) {
try {
observer.directoryCreated(path);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
observer.fileCreated(path);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
if (Files.isRegularFile(path)) {
observer.fileModified(path);
}
} else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
if (Files.isDirectory(path)) {
observer.directoryDeleted(path);
} else {
observer.fileDeleted(path);
}
}
}
}
/**
* 执行线程
*/
class Listner implements Runnable {
private WatchService watcher;
public Listner(WatchService watcher) {
super();
this.watcher = watcher;
}
public void run() {
try {
while (true) {
WatchKey key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path parent = keys.get(key);
Path path = parent.resolve(ev.context());
if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
continue;
}
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE && Files.isDirectory(path)) {
try {
register(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notifyObservers(ev, path);
}
key.reset();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Path path = Paths.get("D:\\pic");
FsWatcher fsWatcher;
try {
fsWatcher = new FsWatcher(path);
SimpleObserver simpleObserver = new SimpleObserver();
fsWatcher.addObserver(simpleObserver);
fsWatcher.run();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.定义文件操作接口以及实现类
import java.nio.file.Path;
/**
* Created by zem on 05/02/16.
*/
public interface ObserverService {
void fileCreated(Path path) throws Exception;
void fileModified(Path path);
void fileDeleted(Path path);
void directoryCreated(Path path) throws Exception;
void directoryModified(Path path);
void directoryDeleted(Path path);
}
import com.study.aes.service.ObserverService;
import lombok.extern.slf4j.Slf4j;
import java.nio.file.Path;
@Slf4j
public class SimpleObserver implements ObserverService {
@Override
public void fileCreated(Path path) throws Exception {
log.info("文件创建,path:{}",path);
}
@Override
public void fileModified(Path path) {
log.info("文件修改,path:{}",path);
}
@Override
public void fileDeleted(Path path) {
log.info("文件删除,path:{}",path);
}
@Override
public void directoryCreated(Path path) throws Exception {
log.info("文件夹创建,path:{}",path);
}
@Override
public void directoryModified(Path path) {
log.info("文件夹修改,path:{}",path);
}
@Override
public void directoryDeleted(Path path) {
log.info("文件夹删除,path:{}",path);
}
}
3.测试代码片段
public static void main(String[] args) {
Path path = Paths.get("D:\\pic");
FsWatcher fsWatcher;
try {
fsWatcher = new FsWatcher(path);
SimpleObserver simpleObserver = new SimpleObserver();
fsWatcher.addObserver(simpleObserver);
fsWatcher.run();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
4.效果如下图