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]); } }