Java   发布时间:2019-10-05  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Java利用WatchService监听文件变化示例大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

在实现配置中心的多种方案中,有基于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]事件

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

大佬总结

以上是大佬教程为你收集整理的Java利用WatchService监听文件变化示例全部内容,希望文章能够帮你解决Java利用WatchService监听文件变化示例所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Java