java - 在 FreeMarker 中使用绝对路径

标签 java linux freemarker

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

最佳答案

我不得不使用绝对路径,因为模板是在 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.
    }

}

初始化是:

public String generate(File template) {

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

    // ...
}

关于java - 在 FreeMarker 中使用绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1208220/

相关文章:

linux - 良好的Gnome/kde/主题开发主题/环境?

linux - 完成的作业运行时间 linux

java - Joda ISODateTimeFormat 不在字符串中使用时区

java - Apache FreeMarker 中的文本格式(首字母大写,其余字母小写)

java - 导航菜单中不同帐户类型的不同菜单

java - `SqlProvider` 如何在 `MyBatis` 中获取超过 1 个参数?

java - Oracle Java : Isn't NLS_TERRITORY enough to correctly format a number?

java - Mockito - 当主类包含许多其他类时模拟的深度?

java - 替换捕获组

c - 如何以不需要收获 child 的方式 fork 过程