【发布时间】:2011-02-25 06:25:39
【问题描述】:
我有一个项目,我想加载一个速度模板来完成它的参数。整个应用程序被打包为一个 jar 文件。我最初的想法是这样的:
VelocityEngine ve = new VelocityEngine();
URL url = this.getClass().getResource("/templates/");
File file = new File(url.getFile());
ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, file.getAbsolutePath());
ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true");
ve.init();
VelocityContext context = new VelocityContext();
if (properties != null) {
stringfyNulls(properties);
for (Map.Entry<String, Object> property : properties.entrySet()) {
context.put(property.getKey(), property.getValue());
}
}
final String templatePath = templateName + ".vm";
Template template = ve.getTemplate(templatePath, "UTF-8");
String outFileName = File.createTempFile("report", ".html").getAbsolutePath();
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outFileName)));
template.merge(context, writer);
writer.flush();
writer.close();
当我在 Eclipse 中运行它时,它工作得很好。但是,一旦我打包程序并尝试使用命令行运行它,我就会收到错误,因为找不到文件。
我想问题出在这一行:
ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, file.getAbsolutePath());
因为在 jar 中绝对文件不存在,因为它在 zip 中,但我还没有找到更好的方法。
有人有什么想法吗?
【问题讨论】:
-
看在上帝的份上,突出显示您帖子中的代码并单击代码按钮,使其格式正确! :)
-
您确定 /templates/ 目录正在导出到您的 jar 中吗?您必须将其标记为构建设置和内容的一部分。
-
不知道代码按钮,谢谢。是的,模板目录正在进入 jar 文件。
标签: java templates jar classpath velocity