2013-06-19 213 views

回答

10

这里是我发现的方法:

private String renderMustacheContent() throws IOException { 
    MustacheFactory mf = new DefaultMustacheFactory(); 
    Mustache mustache; 

    if (type.getTemplate().trim().isEmpty()) {    
     String emailContent = genCpuEmailContent(cmsKey); 
     mustache = mf.compile(new StringReader(emailContent), "cpu.template.email"); 
    } else { 
     mustache = mf.compile(type.getTemplate()); 
    } 

    StringWriter writer = new StringWriter(); 
    mustache.execute(writer, values).flush(); 

    return writer.toString(); 
} 

所以,基本上,当你只是想从一个字符串模板呈现的电子邮件,而而不是文件,只需使用该模板创建新的StringReader即可。

1

如果存储了字符串到使用的FileWriter(或其他类)的文件,并保持扩展.mustache,那么你应该能够关闭并使用该文件。这是我真正掀起了一些东西(它可能不起作用):

//write to the file 
FileUtils.writeStringToFile(new File("template.mustache"), "example mustache stuff"); 
//do stuff.... 
//code for turning template into mustache 
MustacheFactory mf = new DefaultMustacheFactory(); 
Mustache mustache = mf.compile("template.mustache"); 
mustache.execute(new PrintWriter(System.out), new Example()).flush(); 

编辑:我误读了标题。您可以创建一个临时文件,然后再删除它。

来源:

How do I save a String to a text file using Java?

https://github.com/spullara/mustache.java/blob/master/example/src/main/java/mustachejava/Example.java

+0

这对于那些应该很简单的事情来说太过分了。 – iCodeLikeImDrunk

相关问题