使用commons-io-2.0监听文件变化
2018-03-21 20:50:14
783次阅读
0个评论

继承FileAlterationListenerAdaptor 实现它的功能:


import java.io.File;  
  
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;  
import org.apache.commons.io.monitor.FileAlterationObserver;  
import org.slf4j.Logger;  
import org.slf4j.LoggerFactory;  
  
public class FileListerAdapter extends FileAlterationListenerAdaptor {  
    private static final Logger logger = LoggerFactory.getLogger(FileListerAdapter.class);    
      
    @Override  
    public void onFileChange(File file) {  
        if (!file.exists() || !file.canRead()) {  
            logger.info("The file {} is not exists or is not readable!", file);  
            return;  
        }  
        logger.info("----The file {} is change.", file);  
        //TODO 读取操作  
        super.onFileChange(file);  
    }  
  
    @Override  
    public void onFileCreate(File file) {  
        if (!file.exists()) {  
            logger.info("The file {} is not exists!", file);  
            return;  
        }  
        if (!file.canRead()) {  
            logger.info("The file {} is not readable!", file);  
            return;  
        }  
        logger.info("----The file {} is created.", file);  
        //TODO 读取操作  
        super.onFileCreate(file);  
    }  
  
    @Override  
    public void onFileDelete(File file) {  
        logger.info("----The file {} is deleted.", file);  
        super.onFileDelete(file);  
    }  
  
    @Override  
    public void onDirectoryChange(File directory) {  
        if (!directory.exists()) {  
            logger.info("The directory {} is not exists!", directory);  
            return;  
        }  
        logger.info("----The directory {} has changed.", directory);  
        super.onDirectoryChange(directory);  
    }  
  
    @Override  
    public void onDirectoryCreate(File directory) {  
        if (!directory.exists()) {  
            logger.info("The directory {} is not exists!", directory);  
            return;  
        }  
        logger.info("----The directory {} is created.", directory);  
        super.onDirectoryCreate(directory);  
    }  
  
    @Override  
    public void onDirectoryDelete(File directory) {  
        logger.info("----The directory {} is deleted.", directory);       
        super.onDirectoryDelete(directory);  
    }  
}

调用方法:


FileAlterationMonitor monitor = new FileAlterationMonitor(1000L);// 每隔1000毫秒扫描一次  
for (File listenFile:files) {  
    FileAlterationObserver observer = new FileAlterationObserver(listenFile, new FileFilterImpl());  
    FileListerAdapter listener = new FileListerAdapter();  
    observer.addListener(listener);  
    monitor.addObserver(observer);  
}  
monitor.start();

new FileAlterationObserver 的时候还需要使用到一个FileFilter 的接口实现,实现它的accept 方法即可。
这样就可以轻松实现对多个目录的文件监听,需要监听的文件可以使用正则表达式去过滤。

收藏 0 0

登录 后评论。没有帐号? 注册 一个。

admin

官方人员
  • 0 回答
  • 0 粉丝
  • 0 关注