代码:
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class StringTemplateLoader implements TemplateLoader {
private String template;
public StringTemplateLoader(String template) {
this.template = template;
if (template == null) {
this.template = "";
}
}
public Object findTemplateSource(String name) throws IOException {
return new StringReader(template);
}
@Override
public long getLastModified(Object templateSource) {
return 0;
}
public Reader getReader(Object templateSource, String encoding)
throws IOException {
return (Reader) templateSource;
}
public void closeTemplateSource(Object templateSource) throws IOException {
((StringReader) templateSource).close();
}
public static void main(String[] args) throws Exception {
Configuration cfg = new Configuration();
cfg.setTemplateLoader(new StringTemplateLoader("..Hello,${user}!"));
Map root = new HashMap();
root.put("user", "Jack");
StringWriter writer = new StringWriter();
long start = System.currentTimeMillis();
Template template = cfg.getTemplate("");
template.process(root, writer);
System.out.println(System.currentTimeMillis() - start);
System.out.println(writer.toString());
}
}