第一步:导入依赖 <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <dependency> <groupId>velocity-tools</groupId> <artifactId>velocity-tools</artifactId> <version>1.4</version> </dependency>
第二步:模板velocity ( test.vm 中的主要内容)
<td>
第一个 $!date.format("yyyy年MM月dd日",$!createTime)
第二个 $!img.format("yyyy年MM月dd日",$!createTime)
</td>
第三步:代码
VelocityEngine ve = new VelocityEngine();
//设置编码格式
ve.setProperty(VelocityEngine.ENCODING_DEFAULT, "UTF-8");
ve.setProperty(VelocityEngine.INPUT_ENCODING, "UTF-8");
ve.setProperty(VelocityEngine.OUTPUT_ENCODING, "UTF-8");
//模板存放路径(此处放在D盘)
ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, "D://");
// 初始化
ve.init();
// 导入 名为 test.vm 的模板文件(完整路径应为 D://test.vm)
Template template = ve.getTemplate("test.vm");
VelocityContext ctx = new VelocityContext();
//此处的 img、date 对应 第二步的红色部分 若不对应设置格式化将无效
ctx.put("img", new DateTool());
ctx.put("date", new DateTool());
//时间变量 createTime 对应第二步中的蓝色部分 $!createTime 填充变量
ctx.put("createTime", "2019-12-23 17:53:16");
StringWriter sw = new StringWriter();
//合成填充
template.merge(ctx, sw);
String r = sw.toString();
//打印在控制看效果
System.err.println(r);
//输出为html文件看效果
File file = new File("D://new.html");
FileWriter fileWriter = new FileWriter(file);
fileWriter.append(r);
fileWriter.flush();
fileWriter.close();