package watchFile;
/**
* Created by 8pig-16 on 2015/7/1.
*/
public class Test {
public static void main(String [] args){
UpdateFile updateFile=new UpdateFile();
updateFile.register(new UpdateFile.Update() {
public void update(String file) {
System.out.println("更新文件--"+file);
}
});
WatchDir watchDir= null;
try {
watchDir = new WatchDir(updateFile,"E:\\update");
Thread t=new Thread(watchDir);
t.setDaemon(false);
t.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package watchFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
/**
* Created by 8pig-16 on 2015/7/1.
*/
public class WatchDir implements Runnable{
private WatchService watchService;
private UpdateFile updateFile;
//监控某个目录下
public WatchDir(UpdateFile updateFile,String dir) throws Exception{
this.updateFile=updateFile;
//Path path= FileSystems.getDefault().getPath(dir);
Path path= Paths.get(dir);
//获取默认的实现
watchService=FileSystems.getDefault().newWatchService();
//注册监听事件
path.register(watchService,StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
}
//该目录是否是正确的
private boolean isRightDir(String dir){
// 尝试找到配置文件路径
try {
File file = new File(dir).getCanonicalFile();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void run() {
System.out.println("start..");
while(true){
//循环接受事件
try {
System.out.println("run..");
//获取事件类型 add delete modify
WatchKey key=watchService.take();
System.out.println("key.."+key);
//获取事件列表
List<WatchEvent<?>> events= key.pollEvents();
for(WatchEvent event:events){
WatchEvent.Kind kind = event.kind();
if (kind == StandardWatchEventKinds.OVERFLOW)
{// 事件可能lost or discarded
continue;
}
WatchEvent<Path> e = (WatchEvent<Path>) event;
Path fileName = e.context();
// 通知这些变化的
String configFile = String.valueOf(fileName);
//通知观察者
updateFile.notifyInterface(configFile);
// System.out.printf("Event %s has happened,which fileName is %s%n", kind.name(), fileName);
// break;
}
if (!key.reset())
{
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package watchFile;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 8pig-16 on 2015/7/1.
*/
public class UpdateFile {
private List<Update> updates=new ArrayList<Update>();
public void register(Update update){
updates.add(update);
}
public void delete(Update update){
updates.remove(update);
}
public void notifyInterface(String fileName){
for (Update update:updates){
update.update(fileName);
}
}
public interface Update{
public void update(String file);
}
}