监听器:文件/文件夹
当文件/文件夹发生新增或删除就会出发监听器
并可以设置相关操作
比如视频快照,每个照片都要进行算法识别,可以监听该文件夹,一旦有新照片创建,自动调用算法接口。
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import javax.annotation.Resource;
import java.io.File;
import java.util.List;
//@Component
@Slf4j
public class InitFFmpeg implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
runExample("需要监听的 文件/文件夹 URL");
}
public void runExample(String PARENT_DIR) throws java.lang.Exception {
File parentDir = FileUtils.getFile(PARENT_DIR);
FileAlterationObserver observer = new FileAlterationObserver(parentDir);
observer.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileCreate(File file) {
}
@Override
public void onFileDelete(File file) {
}
@Override
public void onDirectoryCreate(File dir) {
System.out.println("Directory created: " + dir.getName());
}
@Override
public void onDirectoryDelete(File dir) {
System.out.println("Directory deleted: " + dir.getName());
}
});
FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);
monitor.start();
}
}