在jar文件中加载速度模板 [英] Loading velocity template inside a jar file

查看:153
本文介绍了在jar文件中加载速度模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,我想加载一个速度模板,用参数完成它。整个应用程序打包为jar文件。我最初想到的是:

I have a project where I want to load a velocity template to complete it with parameters. The whole application is packaged as a jar file. What I initially thought of doing was this:

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中运行它时,这个工作正常。但是,一旦我打包程序并尝试使用命令行运行它,我就会收到错误,因为找不到文件。

And this works fine when I run it in eclipse. However, once I package the program and try to run it using the command line I get an error because the file could not be found.

我想问题就在于此line:

I imagine the problem is in this line:

ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, file.getAbsolutePath());

因为在罐子里绝对文件不存在,因为它在拉链内,但我不能还没找到更好的办法。

Because in a jar the absolute file does not exist, since it's inside a zip, but I couldn't yet find a better way to do it.

任何人都有任何想法吗?

Anyone has any ideas?

推荐答案

如果你想使用classpath中的资源,你应该使用资源加载器来实现类路径:

If you want to use resources from classpath, you should use resource loader for classpath:

ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); 
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());

这篇关于在jar文件中加载速度模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆