【发布时间】:2019-03-17 21:07:44
【问题描述】:
面对一些奇怪的问题, 像这样设置 Velocity Engine。
Properties properties = new Properties();
properties.setProperty(RuntimeConstants.EVENTHANDLER_INCLUDE,IncludeRelativePath.class.getName());
properties.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
properties.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
File f = new File(".");
LOGGER.info("Base class path : {}",f.getCanonicalPath());
//Objects.requireNonNull(resource);
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,f.getCanonicalPath());
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init(properties);
return velocityEngine;
然后我试图获取使用创建的文件:
PrintWriter out = new PrintWriter(templateName+".vm");
out.println(fileContentStr);
out.close();
像这样:
Template t = this.getEngine().getTemplate( fileName + ".vm");
这给了我 ResourceNotFoundException。它在我的本地工作。我没有在任何地方对路径进行硬编码。无法理解为什么它不起作用。请有人可以在这里帮助我。在尝试了所有排列组合后我被卡住了。
Motive : 我只需要能够从项目目录中读取 VM 文件并创建一个。
【问题讨论】:
-
properties.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());这行没用,应该是properties.setProperty("file.resource.loader.class", FileResourceLoader.class.getName());。它至少在本地工作,因为这是此属性的默认值,这不是问题的原因。 -
另外说明:
IncludeRelativePath的目的是让#include() 和#parse() 在与当前模板相同的目录中查找模板。它不适用于您的用例。 -
@ClaudeBrisson 给出了所有要点。我也想问一下模板名称对吗?因为在 windows templatename 不区分大小写的其他人不。如果生产的不是windows怎么办?
-
@soorapadman 你是对的,必须检查区分大小写。我将其添加到我的答案中。