使用freemarker生成文件到本地(main方法)

本文介绍了一个使用Freemarker模板引擎的Java代码示例,展示了如何设置配置、加载模板、处理异常以及填充数据模型来生成HTML文件。

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

   public static void main(String[] args) {
         // Create your Configuration instance, and specify if up to what FreeMarker
        //// version (here 2.3.22) do you want to apply the fixes that are not 100%
        //// backward-compatible. See the Configuration JavaDoc for details.
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 编码格式
        configuration.setDefaultEncoding("UTF-8");
        try {
            // FTL(freemarker templete language)模板所在的文件夹
            configuration.setDirectoryForTemplateLoading(new File("E:\\freemarker"));
            // 异常梳理
            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            Map<String,Object>root = new HashMap<>();
            Map<String,String>user = new HashMap<>();
            root.put("key",user);
            user.put("name","测试");
            // FTL(freemarker templete language)模板所在的文件夹的名称
            Template template = configuration.getTemplate("testFreeMarker.ftl");
            OutputStreamWriter writer = new OutputStreamWriter(System.out);
            File file = new File("E:\\freemarker\\testFreeMarker.html");
            FileWriter fileWriter = new FileWriter(file);
            try {
                template.process(root,fileWriter);
                fileWriter.flush();
                fileWriter.close();
            } catch (TemplateException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值