FreeMarker 乱码解决方案 生成静态html文件

时间:2023-03-09 21:22:19
FreeMarker 乱码解决方案 生成静态html文件

读取模板的时候有一个编码:

Template template = this.tempConfiguration.getTemplate(templatePath,"UTF-8");

生成文件的时候使用编码:

Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));

附(freeMarker生成静态文件的代码):

public class MakeHtml {
private Configuration tempConfiguration = new Configuration(); /**
* 注意:所有位置相对于根目录
* @param path servletPath
* @param data
* @param templatePath 模板路径
* @param targetHtmlPath 保存路径
*/
public void createHTML(String path, Map<String, Object> data,
String templatePath, String targetHtmlPath) {
try {
//filepath:ftl存放路径(/template/file/static)
System.out.println(path);
this.tempConfiguration.setDirectoryForTemplateLoading(new File(path+"/freeMarker"));
//templatePath:ftl文件名称(template.ftl)
Template template = this.tempConfiguration.getTemplate(templatePath,"UTF-8");
// 静态页面要存放的路径
File htmlFile = new File(path + File.separator + targetHtmlPath);
if(!htmlFile.getParentFile().exists()) {
htmlFile.getParentFile().mkdirs();
}
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
// 处理模版 map数据 ,输出流
template.process(data, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
} public void setTempConfiguration(Configuration tempConfiguration) {
this.tempConfiguration = tempConfiguration;
}
}