文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java实现文件监控器FileMonitor

2023-06-02 13:24

关注

  应用场景:

  代码可以实现文件变化后的监听,如文件变化,自动重新加载文件内容,实现配置文件的热部署。

  代码:

  package com.yx.demo.filemonitor;

  import java.io.File;

  import java.lang.ref.WeakReference;

  import java.util.ArrayList;

  import java.util.Collection;

  import java.util.HashMap;

  import java.util.Iterator;

  import java.util.List;

  import java.util.Timer;

  import java.util.TimerTask;

  

  public class FileMonitor {

  

  private static FileMonitor defaultFileMonitor = new FileMonitor(2 * 1000);

  private Timer timer_;

  private HashMap files_; // File -> Long

  private List fileEntrys = new java.util.concurrent.CopyOnWriteArrayList();

  private Collection> listeners_; // of WeakReference(FileListener)

  private long pollingInterval = 10000;

  public static FileMonitor getDefaultFileMonitor() {

  return defaultFileMonitor;

  }

  

  public FileMonitor(long pollingInterval) {

  this.pollingInterval = pollingInterval;

  files_ = new HashMap();

  listeners_ = new ArrayList>();

  timer_ = new Timer("FileMonitor", true);

  timer_.schedule(new FileMonitorNotifier(), 0, pollingInterval);

  }

  

  public void stop() {

  timer_.cancel();

  timer_ = null;

  }

  public void start() {

  if (timer_ == null) {

  timer_ = new Timer(true);

  timer_.schedule(new FileMonitorNotifier(), 0, pollingInterval);

  }

  }

  

  public void addFile(String id, File file) {

  if (!files_.containsKey(file)) {

  FileEntry entry = new FileEntry(id, file, file.exists() ? file.lastModified() : -1);

  files_.put(file, entry);

  }

  }

  

  public void addFileEntry(FileEntry fileEntry) {

  if (!fileEntrys.contains(fileEntry)) {

  fileEntrys.add(fileEntry);

  }

  }

  

  public boolean fileEntryExists(String id) {

  if (id == null) {

  return false;

  }

  for (int i = 0; i < fileEntrys.size(); i++) {

  if (id.equals(fileEntrys.get(i).getId())) {

  return true;

  }

  }

  return false;

  }

  

  public void removeFileEntry(String id) {

  if (id == null) {

  return;

  }

  for (int i = 0; i < fileEntrys.size(); i++) {

  if (id.equals(fileEntrys.get(i).getId())) {

  fileEntrys.remove(i);

  return;

  }

  }

  }

  

  public void removeFile(File file) {

  files_.remove(file);

  }

  

  public void addListener(FileListener fileListener) {

  // Don't add if its already there

  for (Iterator> i = listeners_.iterator(); i.hasNext(); ) {

  WeakReference reference = i.next();

  FileListener listener = (FileListener) reference.get();

  if (listener == fileListener) {

  return;

  }

  }

  // Use WeakReference to avoid memory leak if this becomes the

  // sole reference to the object.

  listeners_.add(new WeakReference(fileListener));

  }

  

  public void removeListener(FileListener fileListener) {

  for (Iterator> i = listeners_.iterator(); i.hasNext(); ) {

  WeakReference reference = (WeakReference) i.next();

  FileListener listener = (FileListener) reference.get();

  if (listener == fileListener) {

  i.remove();

  break;

  }

  }

  }

  郑州治疗妇科哪个医院好 http://www.120kdfk.com/

  private class FileMonitorNotifier extends TimerTask {

  @Override

  public void run() {

  try {

  for (Iterator i = fileEntrys.iterator(); i.hasNext(); ) {

  try {

  FileEntry entry = i.next();

  if (entry == null || !entry.check()) {

  i.remove();

  }

  } catch (Throwable t) {

  t.printStackTrace();

  System.out.println("执行文件监控发生错误:" + t.getMessage());

  }

  }

  // Loop over the registered files and see which have changed.

  // Use a copy of the list in case listener wants to alter the

  // list within its fileChanged method.

  Collection files = new ArrayList(files_.keySet());

  for (Iterator i = files.iterator(); i.hasNext(); ) {

  File file = i.next();

  try {

  FileEntry fileEntry = files_.get(file);

  long lastModifiedTime = fileEntry.getLastModified();

  long newModifiedTime = file.exists() ? file.lastModified() : -1;

  //logger.debug(file.getAbsolutePath());

  //logger.debug(" {}=>{}", lastModifiedTime, newModifiedTime);

  // Chek if file has changed

  if (newModifiedTime != lastModifiedTime) {

  //logger.debug("file changed {})", file.getAbsolutePath());

  fileEntry.setLastModified(newModifiedTime);

  // Register new modified time

  files_.put(file, fileEntry);

  if (fileEntry.getFileListener() != null) {

  fileEntry.getFileListener().fileChanged(fileEntry);

  } else {

  // Notify listeners

  for (Iterator> j =

  listeners_.iterator(); j.hasNext(); ) {

  WeakReference reference =

  (WeakReference) j.next();

  FileListener listener = (FileListener) reference.get();

  // Remove from list if the back-end object has been GC'd

  if (listener == null) {

  j.remove();

  } else {

  listener.fileChanged(fileEntry);

  }

  }

  }

  }

  } catch (Throwable t) {

  if (file != null) {

  t.printStackTrace();

  System.out.println(

  "file monitor execute error, file=" + file.getAbsolutePath() +

  t.getMessage());

  } else {

  System.out.println(

  "file monitor execute error, file=null" + t.getMessage());

  }

  }

  }

  } catch (Throwable t) {

  System.out.println("执行文件监控发生错误" + t.getMessage());

  }

  }

  }

  }

  package com.yx.demo.filemonitor;

  

  public interface FileListener {

  

  public void fileChanged(FileEntry fileEntry);

  }

  package com.yx.demo.filemonitor;

  import java.io.File;

  import java.lang.ref.WeakReference;

  

  public class FileEntry {

  String id;

  File file;

  long lastModified;

  FileListener fileListener = null;

  Object userData;

  WeakReference

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯