监听文件修改

public class WatchFile {

private static final Logger logger = LoggerFactory.getLogger(WatchFile.class);

private ExecutorService executorService = Executors.newSingleThreadExecutor();

private WatchService watchService;

private ConcurrentHashMap<String,List< Callback>> listen = new ConcurrentHashMap<>();

private static WatchFile watchFile;

public static WatchFile getWatchFile() {
    if (watchFile == null) {
        synchronized (watchFile) {
            if (watchFile == null) {
                try {
                    watchFile.watchService = FileSystems.getDefault().newWatchService();
                    watchFile.executorService.execute(new Task());
                } catch (IOException e) {
                    logger.error("WatchFile初始化错误" );
                    e.printStackTrace();
                }
            }
        }
    }
    return watchFile;
}

public void register(String fileName, Callback object) {
    try {
        Paths.get(fileName).register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        List list = listen.get(fileName);
        if(list == null)
           list = new ArrayList()
        list.add(object);
        listen.put(fileName, list);
    } catch (IOException e) {
        logger.error("加入监听失败", fileName);
        e.printStackTrace();
    }
}

static class Task implements Runnable {



    @Override
    public void run() {
        while (true) {
            WatchKey watchKey = null;
            try {
                watchKey = watchFile.watchService.take();
                watchKey.pollEvents().stream().forEach(event -> {
                    WatchEvent<Path> e = (WatchEvent<Path>) event;
                    Path path = e.context();
                    String fileName = path.toFile().getName();
                    List list = watchFile.listen.get(fileName);
                    for(CallBack callback :list){
                         callback.callback();
                    }
                });

            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                watchKey.reset();
            }
        }

    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容