一、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. Docker 搭建 SonarQube

    Docker 搭建 SonarQube Docker 搭建 SonarQube 步骤 创建项目目录 mkdir -p /usr/local/sonarqube && cd /usr/l ...

  2. SPM:Single-stage Multi-person Pose Machines

    figure1图b figure1 -a   figure3-a 图一-a

  3. 前端自适应样式(reset.css)

    @charset "utf-8"; /* CSS Document */ html, body, ul, li, ol, dl, dd, dt, p, h1, h2, h3, h4 ...

  4. 百度小程序中swan.setPageInfo的用法

    现在百度智能小程序是百度最新的流量入口,现在很多做SEO优化.小程序开发的企业为了获取更多的流量不得不开发了,很多的技术人员不了解百度小程序的标题和关键词.描述等信息不知道在哪里设置. 以下是小编给你 ...

  5. Java环境变量配置,HelloWorld。

    一  配置环境变量: 1.右键计算机属性 2.点击高级系统设置 3.点击环境变量 在新建页面,输入变量名“JAVA_HOME”:变量值“你的jdk的路径 在系统变量区域,选择“新建”,输入变量名“CL ...

  6. LeetCode.516 最长回文子序列 详解

    题目详情 给定一个字符串s,找到其中最长的回文子序列.可以假设s的最大长度为1000. 示例 1: 输入: "bbbab" 输出: 4 一个可能的最长回文子序列为 "bb ...

  7. LeetCode 413 Arithmetic Slices详解

    这个开始自己做的动态规划复杂度达到了O(n), 是用的是2维的矩阵来存前面的数据,复杂度太高了, 虽然好理解,但是没效率,后面看这个博客发现没有动态规划做了这个题 也是比较厉害. 转载地址: http ...

  8. github渗透测试工具库[转载]

    前言 今天看到一个博客里有这个置顶的工具清单,但是发现这些都是很早以前就有文章发出来的,我爬下来后一直放在txt里吃土.这里一起放出来. 漏洞练习平台 WebGoat漏洞练习平台:https://gi ...

  9. 基于小程序云Serverless开发微信小程序

    本文主要以使用小程序云Serverless服务开发一个记事本微信小程序为例介绍如何使用小程序云Serverless开发微信小程序.记事本小程序的开发涉及到云函数调用.云数据库存储.图片存储等功能,较好 ...

  10. guice的能力简述

    guice这个google出的bean容器框架,ES有用到他. 能干什么 是一个bean容器 能AOP 能力细分与使用方式 以module创建injector.可以看成是一个容器.Module需要自定 ...