Simple java lib for text templating?

A library-free alternative to the libraries already suggested: java.text.MessageFormat.


You can give Velocity or Freemarker a shot. I've used both in email templating engines. They provide simple syntax for basic use cases, but you can get pretty complex later on!

Of the two, I personally prefer Freemarker because they've done a really good job of providing all sorts of different builtins that make formatting numbers and text very simple.


StringTemplate is another option. The five-minute introduction gives some basic examples and syntax.

StringTemplate hello = new StringTemplate("Hello, $name$",
                                          DefaultTemplateLexer.class);
hello.setAttribute("name", "World");
System.out.println(hello.toString());

It very simple to do it yourself:

public class Substitution {

  public static void main(String[] args) throws Exception {
    String a = "aaaa@bbb@ccc";

    // This can be easiliy FileReader or any Reader
    Reader sr = new StringReader(a);

    // This can be any Writer (ie FileWriter)
    Writer wr = new StringWriter();

    for (;;) {
      int c = sr.read();
      if (c == -1) { //EOF
        break;
      }
      if (c == '@') {
        String var = readVariable(sr);
        String val = getValue(var);
        wr.append(val);
      }
      else {
        wr.write(c);
      }
    }
  }

  /**
   * This finds the value from Map, or somewhere
   */
  private static String getValue(String var)  {
    return null;
  }

  private static String readVariable(Reader sr)throws Exception {
    StringBuilder nameSB = new StringBuilder();
    for (;;) {
      int c = sr.read();
      if (c == -1) {
        throw new IllegalStateException("premature EOF.");
      }
      if (c == '@') {
        break;
      }
      nameSB.append((char)c);
    }
    return nameSB.toString();
  }
}

You have to polish it a little bit, but that's all.