常用工具类--freemarker生成文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013305783/article/details/83140970

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

}

猜你喜欢

转载自blog.csdn.net/u013305783/article/details/83140970