模板和回调模式

package xxx;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.xxx.common.logging.Logger;
import com.xxx.common.logging.LoggerFactory;

/**
 * 文件模板工具类
 * 
 * @author xu.le
 * @version $Id: FileTemplate.java,v 0.1 2010-9-8 上午10:38:23 xu.le Exp $
 */
public class FileTemplate {
    
    
    private static final Logger logger = LoggerFactory.getLogger(FileTemplate.class);

    /**
     * 
     * 
     * @param buffer
     * @param baseDir
     * @param fileName
     */
    public static void upload(final byte[] buffer, final String baseDir, final String fileName) {
        executeTemplate(new CallBack() {
            public OutputStream callBack() {
                File file = new File(baseDir, fileName);
                File parent = file.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                    if (logger.isInfoEnabled()) {
                        logger.info("尝试创建目录:");
                    }
                }
                if (!file.exists()) {
                    OutputStream out = null;
                    try {
                        out = new FileOutputStream(file);
                        out.write(buffer);
                    } catch (FileNotFoundException e) {
                        if (logger.isInfoEnabled()) {
                            logger.info("文件无法找到异常", e);
                        }
                    } catch (IOException e) {
                        if (logger.isInfoEnabled()) {
                            logger.info("文件写入异常", e);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return out;
                }
                if (logger.isInfoEnabled()) {
                    logger.info("文件已经存在,不重新生成,文件为" + file);
                }
                return null;
            }
        });
    }

    /**
     * 
     * @param callBack
     */
    private static void executeTemplate(CallBack callBack) {
        OutputStream out = callBack.callBack();
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                if (logger.isInfoEnabled()) {
                    logger.info("OutputStream close error!", e);
                }
            }
        }
    }

    /**
     * 
     * @author xu.le
     * @version $Id: CallBack.java,v 0.1 2010-9-8 上午10:41:50 xu.le Exp $
     */
    private interface CallBack {

        public OutputStream callBack();
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值