怎么在Java中使用WatchService监控文件内容变化

  介绍

这篇文章将为大家详细讲解有关怎么在Java中使用WatchService监控文件内容变化,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

<强>实现方案

<李>

自己起一个单独线程,定时加载文件,实现较简单,但是无法保证能够实时捕捉文件变化,同时耗CPU

<李>

使用commons-io中的FileAlterationObserver,思想和上面类似,对比前后文件列表的变化,触发对应事件

<李>

JDK 1.7提供的WatchService,利用底层文件系统提供的功能

<强>使用WatchService

WatchService用来监控一个目录是否发生改变,但是可以通过WatchEvent上下文定位具体文件的变化,具体使用过程中要注意以下两点:

<李>

文件改变可能会触发两次事件(我的理解:文件内容的变更,元数据的变更),可以通过文件的时间戳来控制

<李>

在文件变化事件发生后,如果立即读取文件,可能所获内容并不完整,建议的做法判断文件的长度比;0

//,监控文件的变化,重新加载   executor.submit (new  Runnable (), {   @Override才能   public 才能;void 运行(),{   ,,,try  {   ,,,,,final  Path  Path =, FileSystems.getDefault () .getPath (getMonitorDir ());   ,,,,,System.out.println(路径);   ,,,,,final  WatchService  WatchService =, FileSystems.getDefault () .newWatchService ();   ,,,,,final  WatchKey  WatchKey =, path.register (StandardWatchEventKinds.ENTRY_MODIFY watchService也);   ,,,,,while (真实),{   ,,,,,,,final  WatchKey  wk =, watchService.take ();   ,,,,,,,for  (WatchEvent<?祝辞,event :, wk.pollEvents ()), {   ,,,,,,,,,final  Path  changed =,(路径),event.context ();   ,,,,,,,,,Path  absolute =, path.resolve(改变);   ,,,,,,,,,File  configFile =, absolute.toFile ();   ,,,,,,,,,long  lastModified =, configFile.lastModified ();   ,,,,,,,,,logger.info(时间+ lastModified “- - - - - - - - - - - - - - - - -“);   ,,,,,,,,,//,利用文件时间戳,防止触发两次   ,,,,,,,,,if  (changed.endsWith (getLicenseName ()),,,, lastModified  !=, LAST_MOD ,,, configFile.length 祝辞,0),{   ,,,,,,,,,,,logger.info(“- - - - - - - - - - - - - - - - -安康;reloading  - - - - - - - - - - - - - - - - -产生绯闻;);   ,,,,,,,,,,,LAST_MOD =, lastModified;,//,保存上一次时间戳   ,,,,,,,,,,,UPDATED =,真的,,//,设置标志位   ,,,,,,,,,}   ,,,,,,,}      ,,,,,,,if (更新),{   ,,,,,,,,,reloadFile();,//,重新加载   ,,,,,,,}   ,,,,,,,//reset 从而键   ,,,,,,,boolean  valid =, wk.reset ();   ,,,,,,,if (!有效),{   ,,,,,,,,,logger.error (“watch  key 无效!“);   ,,,,,,,}   ,,,,,}   ,,,},catch  (Exception  e), {   ,,,,,logger.error (“;”);   ,,,}   ,,}   });

关于怎么在Java中使用WatchService监控文件内容变化就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看的到。

怎么在Java中使用WatchService监控文件内容变化