近期用java作了個小工具,用了velocity模板生成的方法,在eclipse上運行正常,但打成jar包後總是報錯,以下:Template not found:org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'test.vm';始終不能解決,後搜素髮現Velocity缺省提供了多種讀取模板的方法,終於解決,代碼以下:java
public void velocityInfo(){
VelocityEngine ve = new VelocityEngine();
//可選值:"class"--從classpath中讀取,"file"--從文件系統中讀取
ve.setProperty("resource.loader", "class");
//若是從文件系統中讀取模板,那麼屬性值爲org.apache.velocity.runtime.resource.loader.FileResourceLoader
ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
ve.init();
Template t=ve.getTemplate("net/oschina/www/vm/test.vm");
VelocityContext context = new VelocityContext();
context.put("name", "test");
StringWriter writer = new StringWriter();
t.merge(context, writer);
System.out.println(writer.toString());
}apache
另外,Velocity缺省提供了多種讀取模板的方法,列舉以下,具體內容能夠參考發佈包中的Javadoc:
org.apache.velocity.runtime.resource.loader.JarResourceLoadereclipse
org.apache.velocity.runtime.resource.loader.DataSourceResourceLoader工具
org.apache.velocity.runtime.resource.loader.URLResourceLoaderspa
org.apache.velocity.runtime.resource.loader.StringResourceLoaderip