天天看點

常用工具類--freemarker生成檔案freemarker使用

freemarker使用

  引入包

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import java.io.*;
import java.util.Locale;
import java.util.Map;
           

  列印到控制台(測試用)

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

  輸出到輸出到檔案

public static void printFile(String ftlName, Map<String,Object> root, String outFile, String filePath, String ftlPath) throws Exception{
		try {
//			String base = PathUtil.getClasspath();
//			if(filePath.startsWith("/")) base = "";
			File file = new File(filePath + outFile);
			if(!file.getParentFile().exists()){				//判斷有沒有父路徑,就是判斷檔案整個路徑是否存在
				file.getParentFile().mkdirs();				//不存在就全部建立
			}
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
			Template template = getTemplate(ftlName, ftlPath);
			template.process(root, out);					//模版輸出
			out.flush();
			out.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
           

  通過檔案名加載模版

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

  生成html模闆

public static String makeHtml( String outputPath, FreeMarkerConfigurer freeMarkerConfigurer,PageData pd){
	Configuration configuration = freeMarkerConfigurer.getConfiguration();
	//		configuration.setDefaultEncoding("GBK");
	try {
		Template template = configuration.getTemplate("blog.ftl");//知道模闆檔案
	//			Map root = new HashMap<>();
	//			PageData root = new PageData();
	//			root.put("hello", "hello22211 freemarker");
		// 第八步:建立一個Writer對象,指定生成的檔案儲存的路徑及檔案名。
		File file = new File(outputPath+pd.getString("id")+".html");
		//Writer out = new FileWriter(file);
		Writer out = new PrintWriter(file,"UTF-8");
		// 第九步:調用模闆對象的process方法生成靜态檔案。需要兩個參數資料集和writer對象。
		template.process(pd, out);
		// 第十步:關閉writer對象。
		out.flush();
		out.close();
	} catch (Exception e) {
		e.printStackTrace();
		return "error";
	}

	return "success";

}