java监控文件_Java实现文件夹监控

/**

* 监控指定文件目录

*

* dirPath 指定目录路径

**/

public boolean watchDirectory(String dirPath) {

// 判断要监控的目录是否存在

if (!(new File(dirPath).exists())) {

log.error(MessageFormat.format("目录{0}不存在!", dirPath));

return false;

}

// 注册要监控的文件夹

Path watchDirectory = Paths.get(new File(dirPath).getPath());

try (WatchService watchService = FileSystems.getDefault().newWatchService()) {

watchDirectory.register(watchService,

// 指定要监控的文件操作类型,创建/修改/删除

StandardWatchEventKinds.ENTRY_CREATE);

// 死循环执行监控

while (true) {

// 获取文件操作对象

WatchKey watchKey = watchService.take();

// 针对不同的文件操作类型进行处理

for (WatchEvent event : watchKey.pollEvents()) {

WatchEvent.Kind eventKind = event.kind();

if (eventKind == StandardWatchEventKinds.OVERFLOW) {

continue;

}

// 获取发生改变的文件名

String fileName = event.context().toString();

// 当文件创建执行

if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) {

// TODO: 自定义处理动作

}

}

// 每次执行完后重置

boolean isKeyValid = watchKey.reset();

if (!isKeyValid) {

break;

}

}

} catch (IOException | InterruptedException e) {

e.printStackTrace();

}

return true;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java的WatchService来监控文件夹中新增的文件。WatchService是Java NIO 2中的一个特性,它可以监控文件系统的变化,如文件的创建、修改和删除等。 以下是一个简单的示例代码,用于监控指定文件夹中新增的文件: ```java import java.nio.file.*; public class FolderWatcher { public static void main(String[] args) throws Exception { // 获取文件监控服务 WatchService watchService = FileSystems.getDefault().newWatchService(); // 注册要监控文件夹,并设置监控类型为新增文件 Path folderPath = Paths.get("/path/to/folder"); folderPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); // 循环获取文件变化事件 while (true) { WatchKey watchKey = watchService.take(); // 遍历所有文件变化事件 for (WatchEvent<?> event : watchKey.pollEvents()) { // 判断事件类型是否为新增文件 if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { // 获取新增文件的路径 Path filePath = folderPath.resolve((Path) event.context()); System.out.println("New file created: " + filePath); } } // 重置监控,以便下次继续监控 watchKey.reset(); } } } ``` 在上面的示例代码中,我们首先获取了文件监控服务,并注册了要监控文件夹监控类型。然后,我们进入一个无限循环,在循环中不断获取文件变化事件,并判断事件类型是否为新增文件。如果是新增文件,则输出文件的路径。最后,我们重置监控以便下次继续监控
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值