一、commons-io方法

1、使用Commons-io的monitor下的相关类可以处理对文件进行监控,它采用的是观察者模式来实现的

  • (1)可以监控文件夹的创建、删除和修改
  • (2)可以监控文件的创建、删除和修改
  • (3)采用的是观察者模式来实现的
  • (4)采用线程去定时去刷新检测文件的变化情况

2、引入commons-io包,需要2.0以上。

1
2
3
4
5
6
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

3、编写继承FileAlterationListenerAdaptor的类FileListener。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.File;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.log4j.Logger;
/**
 * 文件变化监听器
 * 在Apache的Commons-IO中有关于文件的监控功能的代码. 文件监控的原理如下:
 * 由文件监控类FileAlterationMonitor中的线程不停的扫描文件观察器FileAlterationObserver,
 * 如果有文件的变化,则根据相关的文件比较器,判断文件时新增,还是删除,还是更改。(默认为1000毫秒执行一次扫描)
 */
public class FileListener extends FileAlterationListenerAdaptor {
  private Logger log = Logger.getLogger(FileListener.class);
  /**
   * 文件创建执行
   */
  public void onFileCreate(File file) {
    log.info("[新建]:" + file.getAbsolutePath());
  }
  /**
   * 文件创建修改
   */
  public void onFileChange(File file) {
    log.info("[修改]:" + file.getAbsolutePath());
  }
  /**
   * 文件删除
   */
  public void onFileDelete(File file) {
    log.info("[删除]:" + file.getAbsolutePath());
  }
  /**
   * 目录创建
   */
  public void onDirectoryCreate(File directory) {
    log.info("[新建]:" + directory.getAbsolutePath());
  }
  /**
   * 目录修改
   */
  public void onDirectoryChange(File directory) {
    log.info("[修改]:" + directory.getAbsolutePath());
  }
  /**
   * 目录删除
   */
  public void onDirectoryDelete(File directory) {
    log.info("[删除]:" + directory.getAbsolutePath());
  }
  public void onStart(FileAlterationObserver observer) {
    // TODO Auto-generated method stub
    super.onStart(observer);
  }
  public void onStop(FileAlterationObserver observer) {
    // TODO Auto-generated method stub
    super.onStop(observer);
  }
}

4、实现main方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static void main(String[] args) throws Exception{
    // 监控目录
    String rootDir = "D:\\apache-tomcat-7.0.78";
    // 轮询间隔 5 秒
    long interval = TimeUnit.SECONDS.toMillis(1);
    // 创建过滤器
    IOFileFilter directories = FileFilterUtils.and(
        FileFilterUtils.directoryFileFilter(),
        HiddenFileFilter.VISIBLE);
    IOFileFilter files    = FileFilterUtils.and(
        FileFilterUtils.fileFileFilter(),
        FileFilterUtils.suffixFileFilter(".txt"));
    IOFileFilter filter = FileFilterUtils.or(directories, files);
    // 使用过滤器
    FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir), filter);
    //不使用过滤器
    //FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir));
    observer.addListener(new FileListener());
    //创建文件变化监听器
    FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
    // 开始监控
    monitor.start();
  }

二、使用JDK7提供的WatchService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public static void main(String[] a) {
    final Path path = Paths.get("D:\\apache-tomcat-7.0.78");
    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
      //给path路径加上文件观察服务
      path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
          StandardWatchEventKinds.ENTRY_MODIFY,
          StandardWatchEventKinds.ENTRY_DELETE);
      while (true) {
        final WatchKey key = watchService.take();
        for (WatchEvent<?> watchEvent : key.pollEvents()) {
          final WatchEvent.Kind<?> kind = watchEvent.kind();
          if (kind == StandardWatchEventKinds.OVERFLOW) {
            continue;
          }
          //创建事件
          if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
            System.out.println("[新建]");
          }
          //修改事件
          if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
            System.out.println("修改]");
          }
          //删除事件
          if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
            System.out.println("[删除]");
          }
          // get the filename for the event
          final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
          final Path filename = watchEventPath.context();
          // print it out
          System.out.println(kind + " -> " + filename);
        }
        boolean valid = key.reset();
        if (!valid) {
          break;
        }
      }
    } catch (IOException | InterruptedException ex) {
      System.err.println(ex);
    }
  }

三、以上方法都可以实现对相应文件夹得文件监控,但是在使用jdk7提供的API时,会出现些许问题。

  • (1)当文件修改时,会被调用两次,即输出两个相同的修改。
  • (2)不能对其子文件夹进行监控,只能提示目录被修改。
  • (3)无法对文件类型进行过滤。

Java实现文件夹下文件实时监控的更多相关文章

  1. python调用另一个文件中的代码,pycharm环境下:同文件夹下文件(.py)之间的调用,出现红线问题

    如何调用另一个python文件中的代码无论我们选择用何种语言进行程序设计时,都不可能只有一个文件(除了“hello world”),通常情况下,我们都需要在一个文件中调用另外一个文件的函数呀数据等等, ...

  2. Projects\Portal_Content\Indexer\CiFiles文件夹下文件占用磁盘空间过大问题。

    C:\Program Files\Microsoft Office Servers\12.0\Data\Office Server\Applications\9765757d-15ee-432c-94 ...

  3. Linux统计某文件夹下文件、文件夹的个数

    统计某文件夹下文件的个数 ls -l |grep "^-"|wc -l 统计某文件夹下目录的个数 ls -l |grep "^d"|wc -l 统计文件夹下文件 ...

  4. Android Studio的使用(十)--读取assets、Raw文件夹下文件,以及menu、drawable文件夹

    1.直接在/src/main目录下面新建assets目录 2.接下来即可读取文件 3.读取Raw文件夹下文件也类似.首先在res文件夹下新建raw目录,然后放入需要的文件即可读取. 4.menu和dr ...

  5. Linux上统计文件夹下文件个数以及目录个数

    对于linux终端用户而言,统计文件夹下文件的多少是经常要做的操作,于我而言,我会经常在谷歌搜索一个命令,“如何在linux统计文件夹的个数”,然后点击自己想要的答案,但是有时候不知道统计文件夹命令运 ...

  6. Linux统计某文件夹下文件的个数

    ls -l |grep "^-"|wc -l 统计某文件夹下目录的个数 ls -l |grep "^d"|wc -l 统计文件夹下文件的个数,包括子文件夹里的 ...

  7. Linux 系统计算文件夹下文件数量数目

    查看某目录下文件的个数(未包括子目录) ls -l |grep "^-"|wc -l 或 find ./company -type f | wc -l 查看某目录下文件的个数,包括 ...

  8. Shell 命令行,写一个自动整理 ~/Downloads/ 文件夹下文件的脚本

    Shell 命令行,写一个自动整理 ~/Downloads/ 文件夹下文件的脚本 在 mac 或者 linux 系统中,我们的浏览器或者其他下载软件下载的文件全部都下载再 ~/Downloads/ 文 ...

  9. Linux 统计文件夹下文件个数及目录个数

    1. 统计文件夹下文件的个数 ls -l | grep "^-" | wc -l 2.统计文件夹下目录的个数 ls -l | grep "^d" | wc -l ...

  10. Linux随笔 - Linux统计某文件夹下文件、文件夹的个数

    统计某文件夹下文件的个数 ls -l |grep "^-"|wc -l 统计某文件夹下目录的个数 ls -l |grep "^d"|wc -l 统计文件夹下文件 ...

随机推荐

  1. JS 图片跟随鼠标移动案例

    css代码 img { position: absolute; /* top: 2px; */ width: 50px; height: 50px; } HTML代码 <img src=&quo ...

  2. HTML基础-06

    网页背景 1.  设置背景颜色          background-color:#bfa; 设置背景图片               background-image:url(“./img/... ...

  3. python设计模式之模板模式

    python设计模式之模板模式 编写优秀代码的一个要素是避免冗余.在面向对象编程中,方法和函数是我们用来避免编写冗余代码的重要工具. 现实中,我们没法始终写出100%通用的代码.许多算法都有一些(但并 ...

  4. Ubuntu18.04安装Nautilus-actions自定义文件管理器鼠标右键列表

    sudo add-apt-repository ppa:daniel-marynicz/filemanager-actions #需要添加源 sudo apt-get install filemana ...

  5. 在eclipse中搜索 datasource.xml 文件:

  6. Mybatis 和 Solon 在一起的升级版

    终于说通 Solon 作者,让他为 Solon 框架添加事务注解支持了:并且把 mybatis-solon-plugin 的 @Df 注解更名为 @Db ,接地气多了(Df是什么鬼呢?新手肯定这么想. ...

  7. python 01 print input int

    学过c语言与c语言的数据结构与算法后再来学习python,感觉编程的核心内容没有变,但每个编程语言都有自己的特点.本次学习的目标是理解python的特点与用法,把学过的bif(内置函数)用法记录下来, ...

  8. JavaScript学习系列博客_29_JavaScript arguments

    arguments (封装实参的对象) 在调用函数时,浏览器每次都会传递进两个隐含的参数:1.函数的上下文对象 this2.封装实参的对象 arguments- arguments是一个类数组对象,它 ...

  9. MySQL最全存储引擎、索引使用及SQL优化的实践

    1 MySQL的体系结构概述 整个MySQL Server由以下组成 :Connection Pool :连接池组件Management Services & Utilities :管理服务和 ...

  10. postman with xdebug

    Set the url with ?XDEBUG_SESSION_START=PHPSTORM and set a header Cookie: XDEBUG_SESSION=PHPSTORM