代码小记
public class FreemarkerUtils {
private static final String TEMPLATE_LOCATION = "/templates";
private static final String HTML_FILE = ".html";
private static Configuration configuration;
static {
configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
configuration.setClassForTemplateLoading(FreemarkerUtils.class, TEMPLATE_LOCATION);
}
public static void generateHtml(Map<String, Object> data, String ftlName) {
BufferedWriter writer = null;
String fileKey = UUID.randomUUID().toString();
try {
Template template = configuration.getTemplate(ftlName);
// 创建HTML
String filePath = "/tmp/".concat(fileKey).concat(HTML_FILE);
if (!Files.exists(Paths.get(filePath))) {
Files.createFile(Paths.get(filePath));
}
writer = Files.newBufferedWriter(Paths.get(filePath));
template.process(data, writer);
} catch (BizException e) {
throw e;
} catch (Exception e) {
throw new BizException(BizErrorCode.SYSTEM_ERROR);
} finally {
if (null != writer) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}