【发布时间】:2014-09-13 02:17:54
【问题描述】:
我正在尝试访问位于 maven 项目的资源文件夹中的文件 (hello.ftl)。
这是试图访问目录的类:
HelloFreemarker.java
package mypackage.main;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
public class HelloFreemarker {
public static void main(String[] args) throws IOException, TemplateException {
Configuration cfg = new Configuration();
cfg.setObjectWrapper(new DefaultObjectWrapper());
cfg.setDirectoryForTemplateLoading(new File("."));
Map<String, Object> model = new HashMap<String, Object>();
model.put("name", "World");
Template template = cfg.getTemplate("hello.ftl");
template.process(model, new OutputStreamWriter(System.out));
}
}
我在控制台中得到的错误如下:
Exception in thread "main" java.io.FileNotFoundException: Template "hello.ftl" not found.
at freemarker.template.Configuration.getTemplate(Configuration.java:742)
at freemarker.template.Configuration.getTemplate(Configuration.java:665)
at mypackage.main.HelloFreemarker.main(HelloFreemarker.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Process finished with exit code 1
【问题讨论】:
-
您是否尝试过使用
HelloFreemarker.class.getResource("hello.ftl");或HelloFreemarker.class.getResource("/hello.ftl");?这假设Configuration#getTemplate接受URL -
要在类路径中获取文件的路径,您必须编写 getClass().getResource("/hello.ftl").getPath()
-
谢谢大家,HelloFreemarket.class.getResource("../..").getPath() 行为我提供了正确的字符串变量,可用作创建新 File() 对象的参数。
-
发布您的解决方案作为帮助他人的正式答案。干得好!
-
好的!我马上发布解决方案!
标签: java maven freemarker