添加依赖
- Gradle
compile('commons-io:commons-io:2.6')
- Maven
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
设置监听器
/**
* @author change
* @since 2024-04-07
*/
@Slf4j
public class FileListener extends FileAlterationListenerAdaptor {
/**
* 轮询开始
*/
@Override
public void onStart(FileAlterationObserver observer) {
System.out.println("轮询开始" );
super.onStart(observer);
}
/**
* 轮询结束
*/
@Override
public void onStop(FileAlterationObserver observer) {
System.out.println("轮询结束" );
super.onStop(observer);
}
/**
* 目录创建
*/
@Override
public void onDirectoryCreate(File directory) {
super.onDirectoryCreate(directory);
System.out.println("目录创建 : " + directory.getPath() + " | " + directory.getName());
}
/**
* 目录修改
*/
@Override
public void onDirectoryChange(File directory) {
super.onDirectoryChange(directory);
System.out.println("目录修改 : " + directory.getPath() + " | " + directory.getName());
}
/**
* 目录删除
*/
@Override
public void onDirectoryDelete(File directory) {
super.onDirectoryDelete(directory);
System.out.println("目录删除 : " + directory.getPath() + " | " + directory.getName());
}
/**
* 文件创建
*/
@Override
public void onFileCreate(File file) {
super.onFileCreate(file);
System.out.println("文件创建 : " + file.getPath() + " | " + file.getName());
}
/**
* 文件修改
*/
@Override
public void onFileChange(File file) {
super.onFileChange(file);
System.out.println("文件修改 : " + file.getPath() + " | " + file.getName());
}
/**
* 文件删除
*/
@Override
public void onFileDelete(File file) {
super.onFileDelete(file);
System.out.println("文件删除 : " + file.getPath() + " | " + file.getName());
}
}
测试程序
这里以SpringBoot自启动任务为例,在应用启动后开始监听目标文件夹。由于监听器在独立的线程中执行,一旦异常发生将导致线程退出,所以如果希望监听线程不中断,应在线程中捕获所有异常。
/**
* @author change
* @since 2024-04-07
*/
@Component
public class FileListenerRunner implements CommandLineRunner {
@Resource
private FileListenerFactory fileListenerFactory;
@Override
public void run(String... args) {
// 创建监听者
FileAlterationMonitor fileAlterationMonitor = fileListenerFactory.getMonitor();
try {
// do not stop this thread
fileAlterationMonitor.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
评论