java - 使用值而不是占位符保存到文件中

标签 java file save velocity placeholder

我使用 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/

相关文章:

linux - 如何递归更改文件名的大小写?

java - 我想序列化和反序列化 ArrayList<Employee> 但我不断收到警告?

java - 对 Paypal 中某些 IPN 消息的无效响应

java - 将空白替换为 %20

c# - 使用 Over TCP 发送多个文件

database - SQLite3 : database not being saved

ios - 尽管指示成功,但 UIDocument 未保存到文件

python - 从压缩字节加载 numpy 数组

java.lang.ClassNotFoundException : com. mysql.jdbc.Driver(maven + jboss)

java - 如何使用 Spring 将 HSQLDB 嵌入到 Web 应用程序的文件中