---
title: "java工程中使用freemarker例子"
author: "cxl2012"
date: "2013-11-21T21:40:40Z"
tags: ["freemarker"]
categories: ["编程语言"]
slug: "java-freemarker"
draft: false
lastmod: "2013-11-21T21:40:40Z"
id: 1936368
url: "https://cxl2012.iteye.com/blog/1936368"
---

新建java project，引入freemarker.jar， 本工程是用的版本：freemarker-2.3.20 版本

java工程目录如下：  
![](http://dl2.iteye.com/upload/attachment/0088/9647/15788730-35a3-3c0b-bfcc-70cc1ed847d7.bmp)

test.ftl文件

```
name : ${name}
age : ${age}
```

 test类

```
package com.freemarker;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Test {
	public static void main(String[] args) throws IOException, TemplateException {

		//1.创建配置实例Cofiguration
		Configuration cfg = new Configuration();

		//2.设置模板文件目录
		//（1）src目录下的目录（template在src下）
		//cfg.setDirectoryForTemplateLoading(new File("src/template"));
		//（2）完整路径（template在src下）
		//cfg.setDirectoryForTemplateLoading(new File(
		//  	"D:/cpic-env/workspace/javaFreemarker/src/template"));
		//cfg.setDirectoryForTemplateLoading(new File("src/template"));
		//（3）工程目录下的目录（template/main在工程下）--推荐
		cfg.setDirectoryForTemplateLoading(new File("template/main"));
		//cfg.setObjectWrapper(new DefaultObjectWrapper());
		//获取模板（template）
		Template template = cfg.getTemplate("test.ftl");
		//建立数据模型（Map）
		Map<String, String> root = new HashMap<String, String>();
		root.put("name", "cxl");
		root.put("age", "25");
		//获取输出流（指定到控制台（标准输出））
		Writer out = new OutputStreamWriter(System.out);
		//StringWriter out = new StringWriter();
		//System.out.println(out.toString());
		//数据与模板合并（数据+模板=输出）
		template.process(root, out);
		out.flush();
	}
}
```

 

运行结果：

```
name : cxl
age : 25
```