Load a resource in Jar

回眸只為那壹抹淺笑 提交于 2019-12-23 17:02:20

问题


Below is structure of my Jar file

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

Inside App.java, I have a line of code that expects me to specify the directory for loading the template.ftl. Something like:

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

and the next line of code, read the template file

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

My problem is that I'm not able to specify the path of directory from where the file will be loaded. The template file to load is available in root of the Jar. When I write,

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

It says, template.ftl not found.

What should be apprpriate code that can set the template directory correctly at Line#1 above?


回答1:


I think this isn't working for you because you're trying to load a file that doesn't exist as a file but is inside your jar. To read your template as an input stream from within the jar file you could do:

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

I think this should help get you onto the right track.




回答2:


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


来源:https://stackoverflow.com/questions/5408981/load-a-resource-in-jar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!