apache commons vfs 文件监控

package test.vfs;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs2.FileChangeEvent;
import org.apache.commons.vfs2.FileListener;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;

/**
 * Hello world!
 * 
 */
public class App {
	public static final Log log = LogFactory.getLog(App.class);

	public static void main(String[] args) {
		FileSystemManager fsManager = null;
		FileObject listendir = null;
		try {
			fsManager = VFS.getManager();
			listendir = fsManager.resolveFile(new File("E://vfs").getAbsolutePath());
		} catch (FileSystemException e) {
			log.error("监视文件夹出错了", e);
			e.printStackTrace();
		}
		
		System.out.println(listendir.getName());
		
		// 定义一个监视器及事件处理程序
		DefaultFileMonitor fm = new DefaultFileMonitor(new FileListener() {
			public void fileCreated(FileChangeEvent event) throws Exception {
				monitor(event);
			}

			public void fileDeleted(FileChangeEvent event) throws Exception {
				monitor(event);
			}

			public void fileChanged(FileChangeEvent event) throws Exception {
				monitor(event);
			}
			
			private void monitor(FileChangeEvent event) {
				FileObject fileObject = event.getFile();
				FileName fileName = fileObject.getName();
				System.out.println(fileName.toString());
			}
		});
		
		
		fm.setRecursive(true); // 设置为级联监控
		fm.addFile(listendir); // 增加监控文件
		fm.start();  // 启动监视器
		
		for(;;){
			try {
				Thread.currentThread().sleep(1000);
				System.out.println(System.currentTimeMillis());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值