package com.ecoman.tlog;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import org.apache.log4j.Logger;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import com.ecoman.weixin.entity.EcoFile;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import javax.annotation.PostConstruct;
@Service
public class TlogWatchService {
private static Logger logger = Logger.getLogger(TlogWatchService.class);
private WatchService watchService;
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
@Autowired
private SystemService systemService;
public TlogWatchService() throws IOException {
Path path = Paths.get(ResourceUtil.getConfigByName("demoUpload"));
this.watchService = FileSystems.getDefault().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
}
public void setThreadPoolTaskExecutor(ThreadPoolTaskExecutor threadPoolTaskExecutor) {
this.threadPoolTaskExecutor = threadPoolTaskExecutor;
}
@PostConstruct
public void handleEvents() throws InterruptedException{
logger.info("开启文件监听服务..."+this);
threadPoolTaskExecutor.execute(new Runnable() {
@Override
public void run() {
try {
while(true){
WatchKey key = watchService.take();
for(WatchEvent<?> event : key.pollEvents()){
Kind<?> kind = event.kind();
if(kind == StandardWatchEventKinds.OVERFLOW){
continue;
}
@SuppressWarnings("unchecked")
WatchEvent<Path> e = (WatchEvent<Path>) event;
Path fileName = e.context();
String name = String.valueOf(fileName);
logger.info("监听到新增文件,文件名:" + name);
if(name.contains(".tlog")){
methodInvoke(name);
}
}
if(!key.reset()){
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
/**
* 解析地防文件tlog为tx文件,并更新文件路径和pause_type状态
* @param fileName
*/
public void methodInvoke(String fileName){
AnalysisTlog.analysisLocation(fileName);
String txFilePath = ResourceUtil.getConfigByName("tlogUpload") + File.separator + fileName.replace("tlog", "tx");
EcoFile ecoFile = systemService.get(EcoFile.class, fileName.substring(0, fileName.indexOf(".")));
ecoFile.setPath(txFilePath);
ecoFile.setPauseType("1");
systemService.saveOrUpdate(ecoFile);
}
}
jdk监听文件系统目录
最新推荐文章于 2021-07-24 11:33:22 发布