简单freeMaker实例
Posted ericguoxiaofeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简单freeMaker实例相关的知识,希望对你有一定的参考价值。
要用的包:
1)新建doc模板:
2)另存为:test.xml
3)nodePad++ 打开 test.xml 并修改其中数据:(解析的时候分开了)
变成
4)保存并改后缀名成ftl:test.ftl
5)上代码
DocumentHandler
package freemaker; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.Template; public class DocumentHandler { private Configuration configuration = null; public DocumentHandler(){ configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); } /** * * @param dataMap 数据 * @param outFilePath 要输出的文件路径(以及文件名) * @param fileName 要获取的文件名 * @return * @throws Exception */ public byte[] createDocArea (Map<String, Object> dataMap ,String outFilePath,String fileName) throws Exception{ this.configuration.setDirectoryForTemplateLoading(new File("d:\\user\\80002795\\桌面\\测试freemaker"));// 取得模板路径 Template template = null; File outFile = null; byte[] bFile = null; try { template = this.configuration.getTemplate(fileName,"UTF-8"); // 取得路径下面的文件名(原始模板已经放在这个对象里面了) } catch (Exception e) { e.printStackTrace(); return null; } outFile = new File(outFilePath); Writer writer = null; FileOutputStream fos = null; try { fos = new FileOutputStream(outFile); OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8"); // 文件输出流转换成字节输出流 writer = new BufferedWriter(osw); } catch (Exception e) { e.printStackTrace(); return null; } try { template.process(dataMap, writer); // 写流 if(outFile!=null){ FileInputStream fis = new FileInputStream(outFile); bFile = new byte[(int) outFile.length()]; fis.read(bFile); fis.close(); } } catch (Exception e) { e.printStackTrace(); return null; }finally{ writer.close(); fos.close(); } return bFile; } }
测试方法:
package freemaker; import java.util.HashMap; import java.util.Map; public class TestMain { public static void main(String[] args) throws Exception { DocumentHandler documentHandler = new DocumentHandler(); Map<String, Object> map = new HashMap<String, Object>(); map.put("name", "guoxiaofeng"); map.put("gender", "boy"); String path = "D:\\test\\hah.doc"; String name = "test.ftl"; documentHandler.createDocArea(map, path, name); } }
6)打开之后,成功:
以上是关于简单freeMaker实例的主要内容,如果未能解决你的问题,请参考以下文章