3

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?

Vicky
  • 5,380
  • 18
  • 60
  • 83

2 Answers2

3

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.

Edd
  • 8,402
  • 14
  • 47
  • 73
  • Template temp = cfg.getTemplate("template.ftl"); .. This line expects to specify the file path. – Vicky Mar 23 '11 at 17:50
  • URL url = this.getClass().getClassLoader().getResource("template.ftl"); File file = new File(url.toURI()); ... that might do the trick – Edd Mar 23 '11 at 18:01
  • Yep.. This is exactly what I derived out of your answer too. Thanks much for detail. – Vicky Mar 23 '11 at 18:03
  • Or this might work... URL url = this.getClass().getClassLoader().getResource(""); File file = new File(url.toURI()); cfg.setDirectoryForTemplateLoading(file); ... I'm just throwing things out there now – Edd Mar 23 '11 at 18:04
0
Line#2: Template temp = cfg.getTemplate("/template.ftl");
Daniel
  • 27,718
  • 20
  • 89
  • 133