Java监控目录变化
1.使用jdk自带的工具
/**
* jdk 自带监控文件目录变化
* @author love
*
*/
public class WatchServiceTest {
public static void main(String[] args) {
final Path path = Paths.get("F:/test");
try(WatchService watch=FileSystems.getDefault().newWatchService()){
path.register(watch,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
while(true) {
final WatchKey key = watch.take();
for(WatchEvent<?> e:key.pollEvents()) {
WatchEvent.Kind<?> kind = e.kind();
if(kind==StandardWatchEventKinds.OVERFLOW) {
continue;
}
if(kind==StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("create");
}
if(kind==StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("delete");
}
if(kind==StandardWatchEventKinds.ENTRY_MODIFY) {
System.out.println("modify");
}
WatchEvent<Path> watchPath = (WatchEvent<Path>)e;
Path filename = watchPath.context();
System.out.println(kind + "---"+filename);
}
boolean valid = key.reset();
if(!valid) {
break;
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
2使用common-io包下的工具
2.下载commons-io 2.x版本
在这里插入代码片
/**
* 使用io包监控文件变化
* @author love
*
*/
public class DirTest {
/**
* 测试使用io包
* @author love
*
*/
private static class FileListener extends FileAlterationListenerAdaptor{
@Override
public void onFileCreate(File file) {
System.out.println("file create....");
}
@Override
public void onFileDelete(File file) {
System.out.println("file delete....");
}
@Override
public void onFileChange(File file) {
System.out.println("file change...");
}
@Override
public void onDirectoryChange(File directory) {
System.out.println("onDirectoryChange");
}
@Override
public void onDirectoryCreate(File directory) {
System.out.println("onDirectoryCreate");
}
@Override
public void onDirectoryDelete(File directory) {
System.out.println("onDirectoryDelete");
}
@Override
public void onStart(FileAlterationObserver observer) {
// System.out.println("onStart");
super.onStart(observer);
}
@Override
public void onStop(FileAlterationObserver observer) {
// System.out.println("onStop");
super.onStop(observer);
}
}
public static void main(String[] args) {
String rootPath = "F:/test";
//轮询时间5s
long interval = TimeUnit.SECONDS.toMillis(1);
//创建过滤器链
IOFileFilter directors = FileFilterUtils.and(FileFilterUtils.directoryFileFilter(),HiddenFileFilter.VISIBLE);
IOFileFilter files = FileFilterUtils.and(FileFilterUtils.fileFileFilter(),FileFilterUtils.suffixFileFilter(".txt"));
IOFileFilter filter = FileFilterUtils.or(directors,files);
//使用过滤器链
FileAlterationObserver observer = new FileAlterationObserver(new File(rootPath), filter);
//不使用过滤器链
observer.addListener(new FileListener());
// FileAlterationObserver observer = new FileAlterationObserver(new File(rootPath));
//创建文件变化监视器
FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
try {
monitor.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}