/** * @注意dataMap裏存放的數據Key值要與模板中的參數相對應 */ public void create(Map<String, Object> dataMap) throws Exception { Configuration configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); // 模板放在com.canyou.template包下面,經過classpath裝載 configuration.setClassForTemplateLoading(this.getClass(), "/com/canyou/template"); Template t = configuration.getTemplate("test.ftl");// 設置要裝載的模板 File outFile = new File(docPath); if (!outFile.exists()) { outFile.createNewFile(); } Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outFile), "utf-8")); t.process(dataMap, out); }
調用的代碼: java
public static void main(String[] args) { Map<String, Object> dataMap = new HashMap<String, Object>();// 要填入模本的數據文件 Grade grade = new Grade(); grade.setSchool("殘友大學"); grade.setMajor("軟件工程專業"); grade.setYear(2011); grade.setAdviser("夏明"); grade.setNo("0102"); grade.setPhoto(getFileStream("D:\\照片\\http_imgload.jpg")); List<Student> list = new ArrayList<Student>(); for (int i = 0; i < 100; i++) { Student stu = new Student(); stu.setNo("0102" + i); stu.setName("test" + i); stu.setSex(i % 2 == 1 ? "男" : "女"); stu.setAge(20 + i % 5); stu.setAddress("廣東省深圳市福田區雨田路1號"); list.add(stu); }
附:Firstobject free XML editor下載地址:http://www.firstobject.com/dn_editor.htm this
freemarker 官網:http://freemarker.org/ 編碼