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);
                }
            }
        }
    
  • 相关阅读:
    如何获取SQL Server数据库连接字符串的某些部分
    .NET同步原语Barrier简介
    模版引擎RazorEngine简介
    如何使用SQL Server实现SignalR的横向扩展
    SignalR的客户端.NET Client介绍
    一个简单的SignalR例子
    看视频学SignalR—在微软虚拟学院学习SignalR
    看视频学Bootstrap—在微软虚拟学院学习Bootstrap
    C# 窗口与控件的相关操作
    opencv——常见的操作
  • 原文地址:https://www.cnblogs.com/xsmhero/p/2882018.html
Copyright © 2011-2022 走看看