利用Velocity模版生成文件

本文介绍了一个使用Velocity模板引擎生成文件的方法。具体展示了如何设置VelocityContext并利用VelocityEngine加载模板,进行数据填充,最终生成目标文件的过程。同时,还涉及了文件备份与编码配置等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private void generateInc(VelocityContext context,String templateFile,String outFile) throws Exception {
        try {
            String encoding = DEFAULT_OUT_FILE_ENCODING;   
            VelocityEngine ve = getEngine();
            Template t = ve.getTemplate(templateFile);
           
            StringWriter writer = new StringWriter();
            t.merge(context, writer);

            if(backupOldInc){
                backupOldInc(distsPath,backupPath,outFile);
            }           
            writeOutFile(writer,outFile,encoding);

            log.info("update " + outFile + "(" + encoding + ") with new value ");
        } catch (Exception e) {
            log.warn("Error when generating overview inc file", e);
            throw e;
        }
    }
   
    /**
     * 根据指定的字符编码返回Velocity Engine。
     * @param encoding 字符编码.Velocity的input 和 output都为此编码。
     */
    private VelocityEngine getEngine() throws Exception{
        String encoding = DEFAULT_OUT_FILE_ENCODING;
        if(vEngine == null){
            vEngine = new VelocityEngine();
            Properties p = new Properties();
            p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatesPath);
            p.setProperty(Velocity.INPUT_ENCODING, encoding);
            p.setProperty(Velocity.OUTPUT_ENCODING, encoding);
            vEngine.init(p);
        }
        return vEngine;
    }
   
    /**
     * 获取默认的Velocity Context.在默认的Velocity Context中默认设置了DateFormat/NumberFormat/Locale以及当前的日期。
     */
    private VelocityContext getDefaultContent(){
        VelocityContext context = new VelocityContext();       
        context.put("date", new DateTool());
        context.put("number", new INumberTool());
        context.put("enLocale", Locale.ENGLISH);
        context.put("gbLocale", Locale.CHINESE);
        context.put("b5Locale", Locale.TAIWAN);
        context.put("today", new Date());
        return context;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值