zoukankan      html  css  js  c++  java
  • 文件监听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);
                }
            }
        }
    
  • 相关阅读:
    [leetcode]Merge Intervals
    ffmpeg错误隐藏框架分析
    [置顶] Hash查找,散列查找
    VS2008LINK : fatal error LNK1000: Internal error during IncrBuildImage
    HDU1257:最少拦截系统(LIS)
    ubuntu系统使用dnw下载程序
    ubuntu系统使用minicom终端操作说明
    uboot显示logo的方式
    在XC2440的uboot中挂载U盘,利用FAT文件系统读写U盘文件
    不知道黑片,千万别说你懂“U盘”-解读Nand Flash
  • 原文地址:https://www.cnblogs.com/xsmhero/p/2882018.html
Copyright © 2011-2022 走看看