当前位置: 移动技术网 > IT编程>开发语言>Java > Java利用WatchService监听文件变化示例

Java利用WatchService监听文件变化示例

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

在实现配置中心的多种方案中,有基于jdk7+的watchservice方法,其在单机应用中还是挺有实践的意义的。

代码如下:

package com.longge.mytest;

import java.io.ioexception;
import java.nio.file.filesystems;
import java.nio.file.path;
import java.nio.file.paths;
import java.nio.file.standardwatcheventkinds;
import java.nio.file.watchevent;
import java.nio.file.watchkey;
import java.nio.file.watchservice;
import java.util.list;

/**
 * 测试jdk的watchservice监听文件变化
 * @author yangzhilong
 *
 */
public class testwatchservice {
  public static void main(string[] args) throws ioexception {
    // 需要监听的文件目录(只能监听目录)
    string path = "d:/test";
    
    watchservice watchservice = filesystems.getdefault().newwatchservice();
    path p = paths.get(path);
    p.register(watchservice, standardwatcheventkinds.entry_modify, 
        standardwatcheventkinds.entry_delete, 
        standardwatcheventkinds.entry_create); 
    
    thread thread = new thread(() -> {
      try { 
        while(true){ 
          watchkey watchkey = watchservice.take(); 
          list<watchevent<?>> watchevents = watchkey.pollevents(); 
          for(watchevent<?> event : watchevents){ 
            //todo 根据事件类型采取不同的操作。。。。。。。 
            system.out.println("["+path+"/"+event.context()+"]文件发生了["+event.kind()+"]事件");  
          } 
          watchkey.reset(); 
        } 
      } catch (interruptedexception e) { 
        e.printstacktrace(); 
      }
    });
    thread.setdaemon(false);
    thread.start();
    
    // 增加jvm关闭的钩子来关闭监听
    runtime.getruntime().addshutdownhook(new thread(() -> {
      try {
        watchservice.close();
      } catch (exception e) {
      }
    }));
  }
}

运行示例结果类似如下:

[d:/test/1.txt]文件发生了[entry_modify]事件
[d:/test/1.txt]文件发生了[entry_delete]事件
[d:/test/新建文本文档.txt]文件发生了[entry_create]事件
[d:/test/新建文本文档.txt]文件发生了[entry_delete]事件
[d:/test/222.txt]文件发生了[entry_create]事件

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网