首先,本人使用到的框架是springboot框架,
实现的功能:项目在启动的时候监听某个文件下是否有新的文件加进来.
package com.nariit.oms.sop.txsbjxsqd.controller;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.*;
import java.util.Timer;
import java.util.TimerTask;
@Component
public class TestController implements ApplicationRunner {
/**
*
* @param applicationArguments
* @throws Exception
*/
//项目启动后执行的方法
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
getFile();
}
private static String path = "E:\\WanWanErYi";
public static void getFile() throws FileNotFoundException, IOException {
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
WatchKey key;
try {
WatchService watchService = FileSystems.getDefault().newWatchService();
Paths.get(path).register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
while (true) {
File file = new File(path);//path为监听文件夹
File[] files = file.listFiles();
System.out.println("等待图片加载!");
key = watchService.take();//没有文件增加时,阻塞在这里
for (WatchEvent<?> event : key.pollEvents()) {
String fileName = path+"\\"+event.context();
System.out.println("增加文件的文件夹路径 :"+fileName);
System.out.println("增加文件的名称 :"+event.context());
}if (!key.reset()) {
break; //中断循环
}
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 2000 , 3000);//第一个数字2000表示,2000ms以后开启定时器,第二个数字3000,表示3000ms后运行一次run
}
}
每次给文件夹添加一个文件:


本文介绍如何使用SpringBoot框架实现项目启动时监听指定文件夹中是否添加了新文件。通过创建监听服务并注册监听事件,当检测到文件夹中有新文件加入时,将输出文件的完整路径和文件名。
633

被折叠的 条评论
为什么被折叠?



