jdk1.7测试可用。加了点无聊的东西帮助阅读。
import java.io.File;
import java.io.IOException;
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;
import java.nio.file.StandardWatchEventKinds;
import org.apache.commons.io.FileUtils;
/**
* 文件事件监听
*/
public class TestWatcherService {
private WatchService watcher;
public TestWatcherService(Path path)throws IOException{
watcher = FileSystems.getDefault().newWatchService();
//注册事件类型 新建文件,删除文件,修改文件
//StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY
path.register(watcher,StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
}
public void handleEvents() throws InterruptedException{
while(true){
WatchKey key = watcher.take();
for(WatchEvent<?> event : key.pollEvents()){
WatchEvent.Kind kind = event.kind();
if(kind == StandardWatchEventKinds.OVERFLOW){//事件可能lost or discarded
continue;
}
WatchEvent<Path> e = (WatchEvent<Path>)event;
//触发事件的文件
Path file = e.context();
String her = "";
if(kind.name().equals(StandardWatchEventKinds.ENTRY_CREATE.name())){
her="创建文件";
}else if(kind.name().equals(StandardWatchEventKinds.ENTRY_DELETE.name())){
her="删除文件";
}else{
her="修改文件";
}
System.out.println("!!!"+her+":"+file.getFileName());
}
if(!key.reset()){
break;
}
}
}
public static void main(String args[]) throws IOException, InterruptedException{
//要监控的路径
String path="c:\\test";
new TestWatcherService(Paths.get(path)).handleEvents();
}
}
按照上述监控路径,在C盘新建test文件夹,在test文件夹下新建文件。输出如下: