文件监听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);

            }

        }

    }


 

你可能感兴趣的:(Monitor)