2011-03-23 98 views
3

下面是我的Jar文件加载资源在罐

root 
- template.ftl 
- org.project.myproject.App.java 

内App.java的结构,我有一个行代码,希望我指定directory用于装载template.ftl。喜欢的东西:

Line#1: cfg.setDirectoryForTemplateLoading("java.io.File object that represents /directory/for/storing/template/files"); 

和下一行代码,读取模板文件

Line#2: Template temp = cfg.getTemplate("template.ftl"); 

我的问题是,我不能指定目录从该文件将被加载路径。要加载的模板文件位于Jar的根目录中。当我写,

cfg.setDirectoryForTemplateLoading(new File(".")); 

它说,template.ftl找不到。

应该在上面的Line#1上正确设置模板目录的应用代码应该是什么?

回答

3

我认为这不适合你,因为你试图加载一个文件不存在作为文件,但是在你的jar中。要从JAR文件中,你可以做你的阅读模板作为输入流:

this.getClass().getClassLoader().getResourceAsStream("template.ftl"); 

我想这应该帮助你在正确的轨道上。

+0

Template temp = cfg.getTemplate(“template.ftl”);此行预计指定文件路径。 – Vicky 2011-03-23 17:50:34

+0

URL url = this.getClass()。getClassLoader()。getResource(“template.ftl”); File file = new File(url.toURI()); ......这可能会诀窍 – Edd 2011-03-23 18:01:38

+0

是的..这正是我从你的答案中衍生出来的。非常感谢细节。 – Vicky 2011-03-23 18:03:00

0
Line#2: Template temp = cfg.getTemplate("/template.ftl");