• 文件监听FileMonitor


    public class FileMonitor {
        
        private static final Logger logger = Logger.getLogger(FileMonitor.class);
        private static FileMonitor instance = null;
        private Timer timer;
        private Map<String, TimerTask> timerEntries;
        
        public FileMonitor() {
            timer = new Timer(true);
            timerEntries = new HashMap<String, TimerTask>();
        }
    
        public static FileMonitor getInstance() {
            if (instance == null) {
                instance = new FileMonitor();
            }
            return instance;
        }
        
        public void cancel() 
        {
            try {
                if (timer != null) {
                    timer.cancel();
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    
        public void addFileChangeListener(FileChangeListener listener,
                String filename, long period) {
            logger.info("开始进行监听文件名[" + filename + "]");
            this.removeFileChangeListener(filename);        
            FileMonitorTask task = new FileMonitorTask(listener, filename);        
            this.timerEntries.put(filename, task);
            this.timer.schedule(task, period, period);
        }
    
        public void removeFileChangeListener(String filename) {
            FileMonitorTask task = (FileMonitorTask) timerEntries.get(filename);
            if (task != null) {
                task.cancel();
            }
        }
    
        private static class FileMonitorTask extends TimerTask {
            private FileChangeListener listener;
            private String filename;
            private File monitorFile;
            private long lastModified;
    
            public FileMonitorTask(FileChangeListener listener, String filename) {
                this.listener = listener;
                this.filename = filename;
                this.monitorFile = new File(filename);
                if (!this.monitorFile.exists()) {
                    return;
                }
                this.lastModified = this.monitorFile.lastModified();
            }
    
            @Override
            public void run() {
                long latestChange = this.monitorFile.lastModified();
                if (latestChange != this.lastModified) {
                    this.lastModified = latestChange;                
                    this.listener.fileChanged(this.filename);
                }
            }
        }
    
  • 相关阅读:
    P2149 [SDOI2009]Elaxia的路线
    电机学第一次课
    大素数区间快判模板
    网络流 最大权闭合子图
    DFS CCPC2017 南宁I题
    稳定婚姻问题模板
    CF438D 线段树 区间求和,区间求膜,单点更新
    对偶图 并查集 BZOJ4423
    BZOJ 1833 数字计数 数位DP
    过一点求对一个直线的垂足
  • 原文地址:https://www.cnblogs.com/xsmhero/p/2882018.html
Copyright © 2020-2023  润新知