面对一些奇怪的问题,像这样设置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。它在我当地工作。我在任何地方都没有硬编码。无法理解为什么它不起作用。请有人试着帮助我。尝试所有排列组合后我陷入困境。
动机:我只需要能够从项目目录中读取VM文件并创建一个。
如果您确定工作目录在构建模板的时间和读取时间之间没有变化,那么在初始化Velocity之前不需要设置任何属性:
IncludeRelativePath
,因为它的目的是让#include()和#parse()在与当前模板相同的目录中找到模板。它不适用于您的用例。file
资源加载器,因为它是默认值。classpath
资源加载器的类,因为你甚至没有使用它我不知道为什么你的代码在本地运行而不是生产。也许工作目录已更改。也许变量templateName
和fileName
不一致。也许模板在编写之前就被要求了。环境之间是否存在重大差异?有安全问题吗?操作系统是否相同?正如Soorapadman指出的那样,它可能是Linux和Windows之间区分大小写的问题。
以下代码应该适用于所有地方:
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init();
PrintWriter out = new PrintWriter("test.vm");
out.println("hello");
out.close();
Template template = velocityEngine.getTemplate("test.vm");