很明显是你的VM无法加载,加载的路径有问题,希望这个例子能帮到你:
package example;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
public class Example {
public Example(String templateFile) {
try {
Velocity.init();
VelocityContext context = new VelocityContext();
Template template = null;
try {
VelocityEngine velocityEngine = new VelocityEngine();
Properties properties = new Properties();
// 也可以在这里指定绝对路径。当指定相对路径时, 在不同的环境下是有区别的。
// 比如把程序部署到tomcat以后,相对路径相对到哪里是个很恶心的事情。
// String basePath = "";
// 可设置绝对路径
String path = this.getClass().getResource("/").toString()
.replaceAll("^file:/", "");
//String basePath = "E:/maven/test/velocity/src/main/resources";
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
velocityEngine.init(properties);
template = velocityEngine.getTemplate("hello.vm");
} catch (ResourceNotFoundException e2) {
System.out.println("cannot find template " + templateFile);
} catch (ParseErrorException e) {
System.out.println("Syntax error in template : " + e);
}
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
System.out));
if (template != null)
template.merge(context, writer);
writer.flush();
writer.close();
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
Example t = new Example(args[0]);
}
}
首先你的'hellovelocity.vm' 要放在src下面,然后代码里面ve.init();前面加上如下两句:
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
希望能帮到大家
Properties p = new Properties();
p.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VelocityEngine ve = new VelocityEngine();//初始化引擎
ve.init(p);
Template t = ve.getTemplate("hellovelocity.vm");//取得模板
'hellovelocity.vm 你的这个资源没法去加载..
hellovelocity.vm
没有找到