1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Apache Velocityでクラスパス上のテンプレートを使用

Posted at

build.gradle
dependencies {
    implementation 'org.apache.velocity:velocity:1.7'
}

/src/main/resources/templates/hoge.vm
key = $key
import java.io.IOException;
import java.io.StringWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

public class Main {

  public static void main(String[] args) {
    Properties p = new Properties();
    p.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    p.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    Velocity.init(p);

    Context context = new VelocityContext();
    context.put("key", "value0001");

    Template template = new Template();
    template = Velocity.getTemplate("templates/hoge.vm", "UTF-8");

    try (StringWriter body = new StringWriter();) {
      template.merge(context, body);
      body.flush();
      System.out.println(body.toString());;
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?