java读取某个目录是否有新增文件(轮询)
使用 commons-io 中的文件监控
jar包:
package org.demo.file; import java.util.concurrent.TimeUnit; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.monitor.FileAlterationMonitor; import org.apache.commons.io.monitor.FileAlterationObserver; /** * 文件监控测试 * @author * @date 2010-11-16 * @file org.demo.file.FileMonitor.java */ public class FileMonitorTest { /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // 监控目录 String rootDir = "d:\\Temp"; // 轮询间隔 5 秒 long interval = TimeUnit.SECONDS.toMillis(5); // FileAlterationObserver observer = new FileAlterationObserver( rootDir, FileFilterUtils.and( FileFilterUtils.fileFileFilter(), FileFilterUtils.suffixFileFilter(".java")), null); observer.addListener(new MyFileListener()); FileAlterationMonitor monitor = new FileAlterationMonitor(interval,observer); // 开始监控 monitor.start(); } }
package org.demo.file; import java.io.File; import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; /** * 自定义文件监听器 * @author * @date 2010-11-16 * @file org.demo.file.MyFileListener.java */ public class MyFileListener extends FileAlterationListenerAdaptor{ @Override public void onFileCreate(File file) { System.out.println("[新建]:" + file.getAbsolutePath()); } @Override public void onFileChange(File file) { System.out.println("[修改]:" + file.getAbsolutePath()); } @Override public void onFileDelete(File file) { System.out.println("[删除]:" + file.getAbsolutePath()); } }