2011-03-23 96 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");