我使用 Apache Velocity,所以我有一个 *.vm 文件,其内容为“Hello $name”。
Velocity.init();
VelocityContext context = new VelocityContext();
context.put("name", "Velocity");
StringWriter w = new StringWriter();
Velocity.mergeTemplate("testtemplate.vm", context, w);
System.out.println(" template : " + w);
这段代码的结果是 -
template : Hello Velocity!
我的任务是将这个结果保存到文件中。我如何保存它,以便在文件中而不是占位符中显示真实值(在本例中为“Hello Velocity!”)。
最佳答案
Velocity.mergeTemplate
接受编写器。在这种情况下,您传递一个 StringWriter
,它只转储字符串中的所有内容。您可以传递一个 FileWriter
来代替,它可以将输出直接保存在目标文件中,或者手动将 w.toString()
; 的结果打印到文件中p>
FileWriter w = new FileWriter("/path/to/targetFile.txt");
Velocity.mergeTemplate("testtemplate.vm", context, w);
w.close();
关于java - 使用值而不是占位符保存到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16592362/