Monitor Folder Or Directory In Spring Boot
Sometimes we need to monitor a directory for changing,adding or deleting files in a given directory.
Spring Boot provides “spring-boot-devtools” with FileSystemWatcher.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
We can create a bean which configures the FileSystemWatcher.
@Configuration
public class FileWatcherConfig {
@Bean
public FileSystemWatcher fileSystemWatcher() {
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(true, Duration.ofMillis(5000L), Duration.ofMillis(3000L));
fileSystemWatcher.addSourceDirectory(new File(“C:/opt”));
fileSystemWatcher.addListener(new MyFileChangeListener());
fileSystemWatcher.start();
System.out.println(“started fileSystemWatcher”);
return fileSystemWatcher;
}
@PreDestroy
public void onDestroy() throws Exception {
fileSystemWatcher().stop();
}
Here we have added a single listener to listen the onchange event i.e. MyFileChangeListener which implements FileChangeListener.
You need to override the onChange() method of FileChangeListener to write a custom logic which will be executed after onChange event occurs in the directory which can be anything including addition of new file, modification of existing file or deletion of file etc.
public class MyFileChangeListener implements FileChangeListener {
@Override
public void onChange(Set<ChangedFiles> changeSet) {
// TODO Auto-generated method stub
for(ChangedFiles cfiles:changeSet) {
for(ChangedFile cfile:cfiles.getFiles()) {
System.out.println(cfile.getType()+”:”+cfile.getFile().getName());
}
}
}}
Here the argument to onChange method i.e Set<ChangedFiles> changeSet is the collection of files that have been changed. Upon iterating this set we get ChangedFile object which has some usefull methods like getType() and getFile(). Method getType() will tells whether the file is added, modified or deleted from given folder.