最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Java利用WatchService监听文件变化示例
时间:2022-06-29 01:10:16 编辑:袖梨 来源:一聚教程网
在实现配置中心的多种方案中,有基于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> 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]事件
相关文章
- 和平精英密室在哪里-和平精英密室具体位置图片 07-02
- 剑星绿洲密码箱在哪-剑星绿洲密码箱位置介绍 07-02
- 绝区零密友同行怎么解锁 绝区零密友同行快速解锁方法 07-02
- 科普:虚拟货币交易所该怎么选?全球虚拟货币交易所排名2025 07-02
- 崩坏星穹铁道白厄光锥怎么搭配 崩坏星穹铁道白厄光锥搭配推荐 07-02
- 暗区突围歼灭竞技场武器防具怎么选 暗区突围歼灭竞技场武器防具选择攻略 07-02