美文网首页
监听文件修改

监听文件修改

作者: 茶瓯 | 来源:发表于2018-05-10 00:03 被阅读0次
    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();
                }
            }
    
        }
    }
    

    相关文章

      网友评论

          本文标题:监听文件修改

          本文链接:https://www.haomeiwen.com/subject/odyarftx.html