根据freemarker 生成html文件(java)

本文介绍如何利用Java与Freemarker模板引擎配合,实现动态生成HTML文件的过程,通过实例代码展示具体步骤。

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

话不多说,直接上代码

 public  File createHtml() throws Exception{
        File outFile = null;
        try {
            // ========================获取模板========================================
            InputStream stream =FreemarkerUtil.class.getClassLoader().getResourceAsStream("person.ftl");  //linux环境下也可用
            File file = File.createTempFile("temp", "html"); // 创建一个空名为temp的临时文件 temp.html
            //流方式将模板文件写入临时文件
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            // 设置相关配置
            Configuration configuration = new Configuration();
            configuration.setDirectoryForTemplateLoading(new File(file.getParent())); // 临时文件所存在的位置
            configuration.setDefaultEncoding("UTF-8");// 默认编码
            Template t = null;
            try {
                t = configuration.getTemplate(file.getName()); // 文件名
                t.setEncoding("UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
            //===========================生成页面========================================
            outFile = new File(file.getParent() +"//"+ System.currentTimeMillis() + ".html");  //文件生成地址(可自己配置)
            Writer out = null;
            try {
                out = new BufferedWriter(new OutputStreamWriter(
                        new FileOutputStream(outFile),"UTF-8"));
            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //模板数据
            HashMap dataMap = new HashMap();  //模板数据
            dataMap.put("number","190108");
            dataMap.put("name","zhangsan");
            dataMap.put("age","18");
            //数据与模板整合写入文件
            t.process(dataMap, out);
            //关闭流
            out.close();
            stream.close();
            //将临时文件删除
            file.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }  finally {
            return outFile;
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值