package com.cn;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
public class FileListener {
public static void main(String[] args) throws Exception {
File directory = new File("H:/test");
// 轮询间隔 5 秒
long interval = TimeUnit.SECONDS.toMillis(5);
// 创建一个文件观察器用于处理文件的格式
FileAlterationObserver observer = new FileAlterationObserver(directory, FileFilterUtils.and(
FileFilterUtils.fileFileFilter(),FileFilterUtils.suffixFileFilter(".txt")));
//设置文件变化监听器
observer.addListener(new MyFileListener());
FileAlterationMonitor monitor = new FileAlterationMonitor(interval,observer);
monitor.start();
}
}
final class MyFileListener implements FileAlterationListener{
@Override
public void onDirectoryChange(File arg0) {
System.out.println("文件目录发生改变!!!");
}
@Override
public void onDirectoryCreate(File arg0) {
System.out.println("文件目录创建成功!!!");
}
@Override
public void onDirectoryDelete(File arg0) {
System.out.println("文件目录已经删除!!!");
}
@Override
public void onFileChange(File arg0) {
System.out.println("文件发生改变!!!");
}
@Override
public void onFileCreate(File arg0) {
System.out.println("文件创建成功!!!");
}
@Override
public void onFileDelete(File arg0) {
System.out.println("文件删除成功!!!");
}
@Override
public void onStart(FileAlterationObserver arg0) {
System.out.println("开始!!!");
}
@Override
public void onStop(FileAlterationObserver arg0) {
System.out.println("停止!!!");
}
}