2013-05-16 32 views
1

我使用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!」)。

回答

2

Velocity.mergeTemplate接受作者。在這種情況下,您傳遞一個StringWriter,它只是將所有內容都轉儲到一個字符串中。您可以通過一個FileWriter來代替,它可以將輸出直接保存在目標文件中,或者手動將結果打印到文件w.toString();

FileWriter w = new FileWriter("/path/to/targetFile.txt"); 
Velocity.mergeTemplate("testtemplate.vm", context, w); 
w.close();