1 Java监控指定目录
问题:Java如何如何监控指定目录文件创建及其修改,删除等操作尼?
Java 利用 WatchService 类,利用操作系统本身的文件监控器对目录和文件进行监控,当被监控对象发生变化时,会有信号通知,从而可以高效的发现变化。
springboot2.0开发环境下核心代码实现
- WatchService 服务类初始化操作
package com.ccbobe.websocket.watch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.WatchService;
/**
* @Author:ccbobe
* 文件目录监控
*/
@Slf4j
@Service
public class FileMonitor implements InitializingBean, DisposableBean {
private WatchService watchService;
@Override
public void destroy() throws Exception {
log.info("文件监控器销毁.....");
if (watchService!=null){
watchService.close();
}
}
@Override
public void afterPropertiesSet() throws Exception {
this.init();
}
public void init() throws IOException {
log.info("文件监控器初始化.......");
this.watchService = FileSystems.getDefault().newWatchService();
}
public WatchService getWatchService() {
return watchService;
}
public void setWatchService(WatchService watchService) {
this.watchService = watchService;
}
}
- 监控核心逻辑代码如下
package com.ccbobe.websocket.watch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.nio.file.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author ccbobe
*/
@Slf4j
@Component
public class CommandRunner implements CommandLineRunner {
@Autowired
private FileMonitor fileMonitor;
private ExecutorService executorService = Executors.newFixedThreadPool(1);
@Override
public void run(String... args) throws Exception {
log.info("开始监控指定文件");
//指定监控文件目录
Path path = Paths.get("C:\\data\\downland\\");
//获取监控服务类
final WatchService watchService = fileMonitor.getWatchService();
//监听创建和删除事件
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE
,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
executorService.submit(()->{
while (true) {
WatchKey watchKey = null;
try {
//阻塞操作
watchKey = watchService.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (WatchEvent event : watchKey.pollEvents()) {
WatchEvent.Kind eventKind = event.kind();
if (eventKind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
String fileName = event.context().toString();
log.info("当前文件变化{}==>{}",fileName,event.kind().name());
//相关业务操作
}
//重置监控器进行下一个文件监控
boolean isKeyValid = watchKey.reset();
if (!isKeyValid) {
break;
}
}
});
}
}
总结:
1 WatchService 编程监控文件变动创建只能监控最新创建、最新修改,最新删除等文件操作,历史文件记录只能监控修改,删除操作;
2 对于指定目录及其子目录下监控有效,目录太深监控无效;