public class VelocityTest {
public static void main(String[] args) {
Properties p = new Properties();
p.put("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
p.put("input.encoding","UTF-8");
Velocity.init(p);
VelocityContext context = new VelocityContext();
context.put("util", new Util());
context.put("date", new Date());
System.out.println(getContentBody(context,"template/test.vm"));
}
protected static String getContentBody(VelocityContext context,String vmFile) {
Template template = null;
try {
template = Velocity.getTemplate(vmFile);
} catch (ResourceNotFoundException rnfe) {
} catch (ParseErrorException pee) {
pee.printStackTrace();
} catch (MethodInvocationException mie) {
} catch (Exception e) {
}
StringWriter sw = new StringWriter();
template.merge(context, sw);
return sw.toString();
}
}
public class Util {
public String format(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
public static void main(String[] args) {
Util r = new Util();
System.out.println(r.format(new Date()));
}
}
test.vm
$util.format($date)