pxkw.hatenadiary.com

めもめも

Hello Velocity Advanced

Hello Velocity
http://pxkw.hatenadiary.com/entry/2013/12/07/113648
をちょっとだけ発展させたもの。

下記2つを実行時に指定させるよう変更

  1. テンプレートファイル
  2. テンプレートに差し込む文字列

コード

HelloVelocityAdvanced.java

package hello;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;


public class HelloVelocityAdvanced{

    public static void say( final String templateFilePath, final String name )
            throws IOException{

        File templateFile = new File(templateFilePath);

        Velocity.setProperty("file.resource.loader.path", templateFile.getParent());
        Velocity.init();
        VelocityContext context = new VelocityContext();

        context.put("name", name);

        Writer   writer   = new StringWriter();
        Template template = Velocity.getTemplate(templateFile.getName(), "UTF-8");
        template.merge(context, writer);

        System.out.print(writer.toString());

        writer.close();
    }

    public static void showUsage(){
        System.out.println("args[0] : /path/to/template.vtl");
        System.out.println("args[1] : your_name");
    }

    public static void main(String[] args) throws IOException {
        if( args.length<2 || args[0].trim().isEmpty() || args[1].trim().isEmpty() ){
            showUsage();
            return;
        }
        HelloVelocityAdvanced.say( args[0], args[1] ); 
    }

}

実行例

$ java -cp (略) hello.HelloVelocityAdvanced res/hello.vtl Velocity
Hello, Velocity!
$ java -cp (略) hello.HelloVelocityAdvanced res/goodnight.vtl Hatena
Good night, Hatena!
$