| ad5081d3  孙向锦
 
初始化项目 | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 |   package com.fh.util;
  
  import java.io.BufferedWriter;
  import java.io.File;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.OutputStreamWriter;
  import java.io.PrintWriter;
  import java.io.Writer;
  import java.util.Locale;
  import java.util.Map;
  
  import freemarker.template.Configuration;
  import freemarker.template.Template;
  import freemarker.template.TemplateException;
  
 | 
| ad5081d3  孙向锦
 
初始化项目 | 17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 |   public class Freemarker {
  
  	/**
  	 * 打印到控制台(测试用)
  	 *  @param ftlName
  	 */
  	public static void print(String ftlName, Map<String,Object> root, String ftlPath) throws Exception{
  		try {
  			Template temp = getTemplate(ftlName, ftlPath);		//通过Template可以将模板文件输出到相应的流
  			temp.process(root, new PrintWriter(System.out));
  		} catch (TemplateException e) {
  			e.printStackTrace();
  		} catch (IOException e) {
  			e.printStackTrace();
  		}
  	}
  	
  	/**
  	 * 输出到输出到文件
  	 * @param ftlName   ftl文件名
  	 * @param root		传入的map
  	 * @param outFile	输出后的文件全部路径
  	 * @param filePath	输出前的文件上部路径
  	 */
  	public static void printFile(String ftlName, Map<String,Object> root, String outFile, String filePath, String ftlPath) throws Exception{
 | 
| ad5081d3  孙向锦
 
初始化项目 | 60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79 |   		}
  	}
  	
  	/**
  	 * 通过文件名加载模版
  	 * @param ftlName
  	 */
  	public static Template getTemplate(String ftlName, String ftlPath) throws Exception{
  		try {
  			Configuration cfg = new Configuration();  												//通过Freemaker的Configuration读取相应的ftl
  			cfg.setEncoding(Locale.CHINA, "utf-8");
  			cfg.setDirectoryForTemplateLoading(new File(PathUtil.getClassResources()+"/ftl/"+ftlPath));		//设定去哪里读取相应的ftl模板文件
  			Template temp = cfg.getTemplate(ftlName);												//在模板文件目录中找到名称为name的文件
  			return temp;
  		} catch (IOException e) {
  			e.printStackTrace();
  		}
  		return null;
  	}
  }
 |