package com.lxzn.backpass; import org.apache.commons.io.monitor.FileAlterationMonitor; import org.apache.commons.io.monitor.FileAlterationObserver; import org.springframework.beans.factory.annotation.Value; import java.io.File; /** * @author clown * * @date 2023/5/25 */ public class FileMonitor { private FileListener fileListener; //监听事件 @Value("${fileNCPath}") private String path ; //监听的文件路径 private FileAlterationMonitor monitor; private long defaultInterval = 10000L; //默认监听的时间间隔 public FileMonitor(String path) { this.path = path; this.monitor = new FileAlterationMonitor(defaultInterval); } public FileMonitor() { this.monitor = new FileAlterationMonitor(defaultInterval); } public FileMonitor(String path, long interval) { this.path = path; this.monitor = new FileAlterationMonitor(interval); } public void setFileListener(FileListener fileListener) { this.fileListener = fileListener; } public void start() { if (monitor == null) { throw new IllegalStateException("Listener must not be null"); } if (path == null) { throw new IllegalStateException("Listen path must not be null"); } FileAlterationObserver observer = new FileAlterationObserver(new File(path)); observer.addListener(fileListener); monitor.addObserver(observer); try { monitor.start(); } catch (Exception e) { e.printStackTrace(); } } }