当前位置: 移动技术网 > IT编程>开发语言>Java > java使用WatchService监控文件夹示例

java使用WatchService监控文件夹示例

2019年07月22日  | 移动技术网IT编程  | 我要评论

踢脚线安装,天庭剩女,诺诺芷琪

通过java7提供的watchservice api 实现对文件夹的监控

package service;

import config.config;
import java.io.ioexception;
import java.nio.file.*;
import java.util.list;
import java.util.concurrent.timeunit;

public class watchdirservice {
  private watchservice watchservice;
  private boolean notdone = true;

  public watchdirservice(string dirpath){
    init(dirpath);
  }

  private void init(string dirpath) {
    path path = paths.get(dirpath);
    try {
      watchservice = filesystems.getdefault().newwatchservice(); //创建watchservice
      path.register(watchservice, 
      standardwatcheventkinds.entry_create,
      standardwatcheventkinds.entry_modify,
      standardwatcheventkinds.entry_delete); //注册需要监控的事件,entry_create 文件创建,entry_modify 文件修改,entry_modify 文件删除
    } catch (ioexception e) {
      e.printstacktrace();
    }
  }

  public void start(){
    system.out.print("watch...");
    while (notdone){
      try {
        watchkey watchkey = watchservice.poll(config.poll_time_out, timeunit.seconds); //此处将处于等待状态,等待检测到文件夹下得文件发生改变,返回watchkey对象
        if(watchkey != null){
          list<watchevent<?>> events = watchkey.pollevents(); //获取所有得事件
          for (watchevent event : events){
            watchevent.kind<?> kind = event.kind(); 
            if (kind == standardwatcheventkinds.overflow){
              //当前磁盘不可用
              continue;
            }
            watchevent<path> ev = event;
            path path = ev.context();
            if(kind == standardwatcheventkinds.entry_create){
              system.out.println("create " + path.getfilename());
            }else if(kind == standardwatcheventkinds.entry_modify){
              system.out.println("modify " + path.getfilename());
            }else if(kind == standardwatcheventkinds.entry_delete){
              system.out.println("delete " + path.getfilename());
            }
          }
          if(!watchkey.reset()){ 
            //已经关闭了进程
            system.out.println("exit watch server");
            break;
          }
        }
      } catch (interruptedexception e) {
        e.printstacktrace();
        return;
      }
    }
  }
}

就是这么简单就可以对一个文件夹进行监控了。

完整带码地址:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网