本文中主要陈述一种实时监听文件夹中是否有文件增加的功能,可用于实际文件上传功能的开发。
主要实现方式:
(1)利用Timer的定时循环执行代码的功能;
(2)利用WatchService实时监听文件夹是否有新文件增加,通过阻塞式IO流实现文件上传服务器。
代码如下:
private static String path = "E:\\Kankan";
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())