如何在 spring 中监视文件夹/目录?

编程入门 行业动态 更新时间:2024-10-27 20:28:49
本文介绍了如何在 spring 中监视文件夹/目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不想在 spring 中编写 Spring Boot 应用程序,它会监视 Windows 中的目录,当我更改子文件夹或添加新文件夹或删除现有文件夹时,我想获取相关信息.

I wan't to write Spring Boot Application in spring which will be monitoring directory in windows, and when I change sub folder or add new one or delete existing one I wanna get information about that.

我该怎么做?我读过这一篇:docs.spring.io/spring-integration/reference/html/files.html以及谷歌spring file watcher"下的每个结果,但我找不到解决方案...

How can i do that? I have read this one: docs.spring.io/spring-integration/reference/html/files.html and each result under 'spring file watcher' in google, but I can't find solution...

你有这样的好文章或例子吗?我不想它喜欢这样:

Do you have a good article or example with something like this? I wan't it to like like this:

@SpringBootApplication @EnableIntegration public class SpringApp{ public static void main(String[] args) { SpringApplication.run(SpringApp.class, args); } @Bean public WatchService watcherService() { ...//define WatchService here } }

问候

推荐答案

spring-boot-devtools 有 FileSystemWatcher

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>

FileWatcherConfig

@Configuration public class FileWatcherConfig { @Bean public FileSystemWatcher fileSystemWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(true, Duration.ofMillis(5000L), Duration.ofMillis(3000L)); fileSystemWatcher.addSourceFolder(new File("/path/to/folder")); fileSystemWatcher.addListener(new MyFileChangeListener()); fileSystemWatcher.start(); System.out.println("started fileSystemWatcher"); return fileSystemWatcher; } @PreDestroy public void onDestroy() throws Exception { fileSystemWatcher().stop(); } }

MyFileChangeListener

@Component public class MyFileChangeListener implements FileChangeListener { @Override public void onChange(Set<ChangedFiles> changeSet) { for(ChangedFiles cfiles : changeSet) { for(ChangedFile cfile: cfiles.getFiles()) { if( /* (cfile.getType().equals(Type.MODIFY) || cfile.getType().equals(Type.ADD) || cfile.getType().equals(Type.DELETE) ) && */ !isLocked(cfile.getFile().toPath())) { System.out.println("Operation: " + cfile.getType() + " On file: "+ cfile.getFile().getName() + " is done"); } } } } private boolean isLocked(Path path) { try (FileChannel ch = FileChannel.open(path, StandardOpenOption.WRITE); FileLock lock = ch.tryLock()) { return lock == null; } catch (IOException e) { return true; } } }

更多推荐

如何在 spring 中监视文件夹/目录?

本文发布于:2023-11-11 21:32:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579608.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件夹   目录   如何在   spring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!