根据freemarker 生成html文件(java)

话不多说,直接上代码

 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;
        }
    }

 

你可能感兴趣的:(java,freemarker,html)