2011/09/11

[Java] Velocityを使用してファイルを作成する方法

概要

Velocityというテンプレートエンジンを使用して、ファイルを作成する方法について説明します。

内容

以下の手順でテンプレートエンジンからファイルを作成することができます。
1.テンプレートエンジンを初期化する
2.テンプレートに渡すパラメータを設定する
3.テンプレートのマージ結果をStringWriterに設定する

以下サンプルコードです。
  1. private File createGroovyScript(FormulaDTO dto) throws Exception {  
  2.   
  3.         File file = File.createTempFile("priceCalc", ".groovy", new File("."));  
  4.   
  5.         // Velocityテンプレートエンジンを初期化する  
  6.         Velocity.init();  
  7.   
  8.         // テンプレートに渡すパラメータを設定する  
  9.         VelocityContext context = new VelocityContext();  
  10.         context.put("formula", dto);  
  11.   
  12.         // テンプレートのマージ結果をStringWriterに設定する  
  13.         StringWriter sw = new StringWriter();  
  14.         Template template = Velocity.getTemplate("/template/template_groovy.vm", "UTF-8");  
  15.         template.merge(context,sw);  
  16.   
  17.         // 結果を一時ファイルに設定する  
  18.         FileWriter writer = new FileWriter(file);  
  19.         writer.write(sw.toString());  
  20.         writer.close();  
  21.   
  22.         return file;  
  23.     }  

template_groovy.vm
  1. import jp.co.technos.common.dto.FormulaDTO;  
  2.   
  3. def calculate(FormulaDTO data) {  
  4.     data.setResult(${formula.formula})  
  5. }  
  6.   
  7. FormulaDTO data = (FormulaDTO) formula  
  8. calculate(data)  

0 件のコメント:

コメントを投稿