简体   繁体   中英

File not found exception when trying to get the ftl template

I wrote a java program in which I have to render a ftl and get the output in String variable. Please find my code below:

Configuration cfg = new Configuration();
StringWriter stringWriter = new StringWriter();
try 
{
       Template template = cfg.getTemplate("src/response.get.html.ftl");
       model.put("content",contextModel);
       template.process(model, stringWriter);
       System.out.println(stringWriter);

} 

But am getting file not found exception in Template template = cfg.getTemplate("src/response.get.html.ftl");

I have placed my response file in src and my java file in package com.test.webscripts . According to http://viralpatel.net/blogs/freemaker-template-hello-world-tutorial/ its fine. But am unable to figure out why am I getting the exception. Can someone please help me?

Thanks in advance!

Generally src is not accessible on runtime, as it's only there for the compiler and the other build tools. After the build was done, the application should only depend on the output of the build (the "binary"), even when in the IDE the src is still there (unlike when you deploy the application).

Also, you haven't shown what TemplateLoader are you using. You should probably do something like this:

cfg.setClassForTemplateLoading(SomeClassInMyApp.class, "/");

and then:

cfg.getTemplate("response.get.html.ftl");

It's a safer practice to create a subdirectory, let's say com/mycompany/myapp/templates , and put the templates there. In that case you need this:

cfg.setClassForTemplateLoading(SomeClassInMyApp.class, "/com/mycompany/myapp/templates");

Note that then cfg.getTemplate("response.get.html.ftl" remains unchanged, as there you specify the path relatively to the template directory.

Please check your PATH environment variable, Is it contains the path of your workspace and your project path? if not that may cause to that error.

Another easy way to solve your error is to change the path in the following line:

Template template = cfg.getTemplate("src/response.get.html.ftl");

Instead of the 'src/response.get.html.ftl' insert the full path from the root directory to your file. ie: 'c://workspac/username/com/companyname/projectName/src/response.get.html.ftl'

Note: If you are working with windows make sure your file has no hidden extension .

我建议您使用 getResource() 方法,例如,在这种情况下:

setIconImage(Toolkit.getDefaultToolkit().getImage(Menu.class.getResource("/resource/profut_1.PNG")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM