当前位置: 首页 > news >正文

java watch service_Java WatchService API 教程

在此示例中,我们将学习使用Java 8 WatchService API观察目录及其中的所有子目录和文件。

How to register Java 8 WatchService

要注册WatchService ,请获取目录路径并使用path.register()方法。

Path path = Paths.get(".");

WatchService watchService = path.getFileSystem().newWatchService();

path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

Watching for change events

要获取发生在目录和其中文件上的更改,请使用watchKey.pollEvents()方法,该方法以流的形式返回所有更改事件的集合。WatchKey watchKey = null;

while (true) {

watchKey = watchService.poll(10, TimeUnit.MINUTES);

if(watchKey != null) {

watchKey.pollEvents().stream().forEach(event -> System.out.println(event.context()));

}

watchKey.reset();

}

该密钥一直有效,直到:通过调用其cancel方法显式地取消它,或者

隐式取消,因为该对象不再可访问,或者

通过关闭手表服务。

如果要在循环中多次使用同一键来多次获取更改事件,请不要忘记调用watchKey.reset()方法,该方法watchKey.reset()键再次设置为ready状态。请注意,诸如如何检测事件,其及时性以及是否保留其顺序之类的几件事高度依赖于底层操作系统。 某些更改可能导致一个操作系统中的单个条目,而类似的更改可能导致另一操作系统中的多个事件。

Watch Directory, Sub-directories and Files for Changes Example

在此示例中,我们将看到一个观看目录的示例,该目录中包含所有子目录和文件。 我们将维护监视键和目录Map keys以正确识别已修改的目录。

下面的方法将向观察者注册一个目录,然后将目录和密钥存储在地图中。

private void registerDirectory(Path dir) throws IOException

{

WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

keys.put(key, dir);

}

在遍历目录结构并为遇到的每个目录调用此方法时,将递归调用此方法。private void walkAndRegisterDirectories(final Path start) throws IOException {

// register directory and sub-directories

Files.walkFileTree(start, new SimpleFileVisitor() {

@Override

public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {

registerDirectory(dir);

return FileVisitResult.CONTINUE;

}

});

}

请注意,无论何时创建新目录,我们都会在watchservice中注册该目录,并将新密钥添加到地图中。WatchEvent.Kind kind = event.kind();

if (kind == ENTRY_CREATE) {

try {

if (Files.isDirectory(child)) {

walkAndRegisterDirectories(child);

}

} catch (IOException x) {

// do something useful

}

}

将以上所有内容与处理事件的逻辑放在一起,完整的示例如下所示:package com.howtodoinjava.examples;

import static java.nio.file.StandardWatchEventKinds.*;

import java.io.IOException;

import java.nio.file.FileSystems;

import java.nio.file.FileVisitResult;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.SimpleFileVisitor;

import java.nio.file.WatchEvent;

import java.nio.file.WatchKey;

import java.nio.file.WatchService;

import java.nio.file.attribute.BasicFileAttributes;

import java.util.HashMap;

import java.util.Map;

public class Java8WatchServiceExample {

private final WatchService watcher;

private final Map keys;

/**

* Creates a WatchService and registers the given directory

*/

Java8WatchServiceExample(Path dir) throws IOException {

this.watcher = FileSystems.getDefault().newWatchService();

this.keys = new HashMap();

walkAndRegisterDirectories(dir);

}

/**

* Register the given directory with the WatchService; This function will be called by FileVisitor

*/

private void registerDirectory(Path dir) throws IOException

{

WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

keys.put(key, dir);

}

/**

* Register the given directory, and all its sub-directories, with the WatchService.

*/

private void walkAndRegisterDirectories(final Path start) throws IOException {

// register directory and sub-directories

Files.walkFileTree(start, new SimpleFileVisitor() {

@Override

public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {

registerDirectory(dir);

return FileVisitResult.CONTINUE;

}

});

}

/**

* Process all events for keys queued to the watcher

*/

void processEvents() {

for (;;) {

// wait for key to be signalled

WatchKey key;

try {

key = watcher.take();

} catch (InterruptedException x) {

return;

}

Path dir = keys.get(key);

if (dir == null) {

System.err.println("WatchKey not recognized!!");

continue;

}

for (WatchEvent> event : key.pollEvents()) {

@SuppressWarnings("rawtypes")

WatchEvent.Kind kind = event.kind();

// Context for directory entry event is the file name of entry

@SuppressWarnings("unchecked")

Path name = ((WatchEvent)event).context();

Path child = dir.resolve(name);

// print out event

System.out.format("%s: %s\n", event.kind().name(), child);

// if directory is created, and watching recursively, then register it and its sub-directories

if (kind == ENTRY_CREATE) {

try {

if (Files.isDirectory(child)) {

walkAndRegisterDirectories(child);

}

} catch (IOException x) {

// do something useful

}

}

}

// reset key and remove from set if directory no longer accessible

boolean valid = key.reset();

if (!valid) {

keys.remove(key);

// all directories are inaccessible

if (keys.isEmpty()) {

break;

}

}

}

}

public static void main(String[] args) throws IOException {

Path dir = Paths.get("c:/temp");

new Java8WatchServiceExample(dir).processEvents();

}

}

运行该程序并在给定输入中更改文件和目录后,您将在控制台中注意到捕获的事件。Output:

ENTRY_CREATE: c:\temp\New folder

ENTRY_DELETE: c:\temp\New folder

ENTRY_CREATE: c:\temp\data

ENTRY_CREATE: c:\temp\data\New Text Document.txt

ENTRY_MODIFY: c:\temp\data

ENTRY_DELETE: c:\temp\data\New Text Document.txt

ENTRY_CREATE: c:\temp\data\tempFile.txt

ENTRY_MODIFY: c:\temp\data

ENTRY_MODIFY: c:\temp\data\tempFile.txt

ENTRY_MODIFY: c:\temp\data\tempFile.txt

ENTRY_MODIFY: c:\temp\data\tempFile.txt

这就是使用Java 8 WatchService API监视文件更改并进行处理的简单示例。

Resources:

相关文章:

  • deepin 15.4 mysql_Deepin 15.4 编译安装 LNMP(PHP 5.6.31 + Nginx 1.12.1 + MySQL 5.6.36)
  • java if else嵌套_替代嵌套If Else语句
  • oom java问题_Java OOM问题如何排查
  • java 视图对象_java – 从不同资源创建视图对象的最佳方法(模式?)
  • java where函数_CONSTRUCT / WHERE中的SPARQL函数
  • mysql上机考试_SQL上机试题及步骤
  • 2d unity 多物体 射线_Unity 2D射线与 3D射线 UI射线
  • java数据如何显示在HTML界面_ajax接收后台数据在html页面显示
  • java mqtt broker_mqtt broker集合
  • notes 发邮件was配置java_Java程序调用LotusNotes邮件服务发送邮件的实现
  • java this 逸出_this引用逸出
  • java单机多核怎么实现的_JAVA实现对于多核CPU的OS满足CPU使用率在50%左右以及实现CPU使用率为正弦曲线-Go语言中文社区...
  • java序列化第二次出错_1.2.28反序列化类bug java.lang.VerifyError:
  • java对mysql读写权限设置_Mac 配置java版本 ---- MySql数据库权限设置 --- openfire
  • java中英对比_中英文代码对比系列之Java一例
  • 【译】理解JavaScript:new 关键字
  • 4月23日世界读书日 网络营销论坛推荐《正在爆发的营销革命》
  • Android框架之Volley
  • Android优雅地处理按钮重复点击
  • ComponentOne 2017 V2版本正式发布
  • ECMAScript 6 学习之路 ( 四 ) String 字符串扩展
  • ES6--对象的扩展
  • HomeBrew常规使用教程
  • JavaScript 一些 DOM 的知识点
  • leetcode98. Validate Binary Search Tree
  • maya建模与骨骼动画快速实现人工鱼
  • nodejs:开发并发布一个nodejs包
  • PAT A1017 优先队列
  • python学习笔记-类对象的信息
  • vue总结
  • 基于Mobx的多页面小程序的全局共享状态管理实践
  • 前端js -- this指向总结。
  • 微服务入门【系列视频课程】
  • 一个JAVA程序员成长之路分享
  • 在Unity中实现一个简单的消息管理器
  • MyCAT水平分库
  • UI设计初学者应该如何入门?
  • #stm32驱动外设模块总结w5500模块
  • (1)Android开发优化---------UI优化
  • (备忘)Java Map 遍历
  • (二)springcloud实战之config配置中心
  • (附源码)spring boot球鞋文化交流论坛 毕业设计 141436
  • (附源码)springboot 校园学生兼职系统 毕业设计 742122
  • (附源码)springboot建达集团公司平台 毕业设计 141538
  • (附源码)ssm高校实验室 毕业设计 800008
  • (一)spring cloud微服务分布式云架构 - Spring Cloud简介
  • (转)德国人的记事本
  • .chm格式文件如何阅读
  • .L0CK3D来袭:如何保护您的数据免受致命攻击
  • .NET 5.0正式发布,有什么功能特性(翻译)
  • .net core MVC 通过 Filters 过滤器拦截请求及响应内容
  • .Net Core 中间件验签
  • .NET 将多个程序集合并成单一程序集的 4+3 种方法
  • .net经典笔试题
  • .NET设计模式(2):单件模式(Singleton Pattern)