监控目录下的文件的变化,使用的onFilexxx事件,而非onDirectoryxxx事件
可以直接运行的代码:
import java.io.File; import java.io.FileFilter; import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; import org.apache.commons.io.monitor.FileAlterationMonitor; import org.apache.commons.io.monitor.FileAlterationObserver; /** * @author root * */ public class MyFileListener extends FileAlterationListenerAdaptor { /** * File system observer started checking event. */ @Override public void onStart(FileAlterationObserver observer) { super.onStart(observer); System.out.println("begin"); } /** * File system observer finished checking event. */ @Override public void onStop(FileAlterationObserver observer) { super.onStop(observer); System.out.println("end"); } @Override public void onFileCreate(File file) { System.out.println("onFileCreate:" + file.getName()); } @Override public void onFileChange(File file) { System.out.println("onFileChange : " + file.getName()); } public static void main(String[] args) { try { // 构造观察类主要提供要观察的文件或目录,当然还有详细信息的filter FileAlterationObserver observer = new FileAlterationObserver("/home/share/", new FileFilter() { @Override public boolean accept(File pathname) { return true; } }); MyFileListener listener = new MyFileListener(); // 为观察对象添加收听对象 observer.addListener(listener); // 配置Monitor,第一个参数单位是毫秒,是监听的间隔;第二个参数就是绑定我们之前的观察对象。 FileAlterationMonitor fileMonitor = new FileAlterationMonitor(3000, new FileAlterationObserver[] { observer }); // 启动开始监听 fileMonitor.start(); } catch (Exception e) { e.printStackTrace(); } } }