使用FreeMarker的绝对路径

dim*_*414 1 java linux freemarker

我一直在使用FreeMarker一段时间,但有一个明显的功能要么丢失,要么我想不出来(我希望后者!).如果你传递cfg.getTemplate()一个绝对路径,它就行不通.我知道你可以指定一个模板目录,但我负担不起,我的用例可以处理任何目录中的文件.有没有办法设置FreeMarker以任何用户期望的方式呈现绝对路径?

Vla*_*mir 6

我必须使用绝对路径,因为模板在Ant脚本中发生,模板在文件系统上并使用Ant文件集发现.我想这些都是一些独特的要求......

无论如何,对于后代(只要SO上升),这是一个有效的解决方案:

public class TemplateAbsolutePathLoader implements TemplateLoader {

    public Object findTemplateSource(String name) throws IOException {
        File source = new File(name);
        return source.isFile() ? source : null;
    }

    public long getLastModified(Object templateSource) {
        return ((File) templateSource).lastModified();
    }

    public Reader getReader(Object templateSource, String encoding)
            throws IOException {
        if (!(templateSource instanceof File)) {
            throw new IllegalArgumentException("templateSource is a: " + templateSource.getClass().getName());
        }
        return new InputStreamReader(new FileInputStream((File) templateSource), encoding);
    }

    public void closeTemplateSource(Object templateSource) throws IOException {
        // Do nothing.
    }

}
Run Code Online (Sandbox Code Playgroud)

初始化是:

public String generate(File template) {

    Configuration cfg = new Configuration();
    cfg.setTemplateLoader(new TemplateAbsolutePathLoader());
    Template tpl = cfg.getTemplate(template.getAbsolutePath());

    // ...
}
Run Code Online (Sandbox Code Playgroud)