add WatchAction

This commit is contained in:
Looly 2020-08-02 20:38:04 +08:00
parent 758626a482
commit 0dcf4f9aca
3 changed files with 45 additions and 7 deletions

View File

@ -10,6 +10,7 @@
* 【core 】 StrUtil增加filter方法pr#149@Gitee
* 【core 】 DateUtil增加beginOfWeek重载
* 【core 】 将有歧义的BeanUtil.mapToBean方法置为过期使用toBean方法
* 【core 】 添加WatchAction对Watcher的抽象
### Bug修复#
* 【core 】 修复原始类型转换时,转换失败没有抛出异常的问题

View File

@ -0,0 +1,24 @@
package cn.hutool.core.io.watch;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
/**
* 监听事件处理函数接口
*
* @author looly
* @since 5.4.0
*/
@FunctionalInterface
public interface WatchAction {
/**
* 事件处理通过实现此方法处理各种事件
*
* 事件可以调用 {@link WatchEvent#kind()}获取对应事件见{@link WatchKind}
*
* @param event 事件
* @param currentPath 事件发生的当前Path路径
*/
void doAction(WatchEvent<?> event, Path currentPath);
}

View File

@ -129,10 +129,11 @@ public class WatchServer extends Thread implements Closeable, Serializable {
/**
* 执行事件获取并处理
*
* @param watcher {@link Watcher}
* @param action 监听回调函数实现此函数接口用于处理WatchEvent事件
* @param watchFilter 监听过滤接口通过实现此接口过滤掉不需要监听的情况null表示不过滤
* @since 5.4.0
*/
public void watch(Watcher watcher, Filter<WatchEvent<?>> watchFilter) {
public void watch(WatchAction action, Filter<WatchEvent<?>> watchFilter) {
WatchKey wk;
try {
wk = watchService.take();
@ -142,15 +143,28 @@ public class WatchServer extends Thread implements Closeable, Serializable {
}
final Path currentPath = watchKeyPathMap.get(wk);
WatchEvent.Kind<?> kind;
for (WatchEvent<?> event : wk.pollEvents()) {
kind = event.kind();
for (WatchEvent<?> event : wk.pollEvents()) {
// 如果监听文件检查当前事件是否与所监听文件关联
if (null != watchFilter && false == watchFilter.accept(event)) {
continue;
}
action.doAction(event, currentPath);
}
wk.reset();
}
/**
* 执行事件获取并处理
*
* @param watcher {@link Watcher}
* @param watchFilter 监听过滤接口通过实现此接口过滤掉不需要监听的情况null表示不过滤
*/
public void watch(Watcher watcher, Filter<WatchEvent<?>> watchFilter) {
watch((event, currentPath)->{
WatchEvent.Kind<?> kind = event.kind();
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
watcher.onCreate(event, currentPath);
} else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
@ -160,8 +174,7 @@ public class WatchServer extends Thread implements Closeable, Serializable {
} else if (kind == StandardWatchEventKinds.OVERFLOW) {
watcher.onOverflow(event, currentPath);
}
}
wk.reset();
}, watchFilter);
}
/**