Velocity默認是加載文件系統中的模板,如果希望加載classpath下的模板的話,需要更換他的加載器
Properties properties=new Properties();
//設置velocity資源加載方式爲class
properties.setProperty("resource.loader", "class");
//設置velocity資源加載方式爲file時的處理類
properties.setProperty("class.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngine ve = new VelocityEngine(properties);
默認情況是加載文件系統
VelocityEngine ve = new VelocityEngine();
//設置參數
ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatepath);//加載文件系統
另附完整代碼
Properties properties=new Properties();
//設置velocity資源加載方式爲class
properties.setProperty("resource.loader", "class");
//設置velocity資源加載方式爲file時的處理類
properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngine ve = new VelocityEngine(properties);
//設置參數
// ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatepath);
//處理中文問題
ve.setProperty(Velocity.INPUT_ENCODING,"utf-8");
ve.setProperty(Velocity.OUTPUT_ENCODING,"utf-8");
try {
//初始化模板
ve.init();
//Velocity模板的名稱
Template template = ve.getTemplate(templatename,"utf-8");
Writer mywriter = new PrintWriter(outfile,"utf-8");
template.merge(vc, mywriter);
mywriter.flush();
mywriter.close();
} catch (Exception e) {
e.printStackTrace();
logger.error("寫模板文件"+templatename+"失敗", e);
throw e;
}