FileNotFoundException when loading freemarker template in java
FreeMarker template paths are resolved by a TemplateLoader
object, which you should specify in the Configuration
object. The path that you specify as the template path is interpreted by the TemplateLoader
, and is usually relative to some kind of base directory (even if it starts with /
), that's also called the template root directory for this reason. In your example, you haven't specified any TemplateLoader
, so you are using the default TemplateLoader
, which is only there for backward-compatibility, and is nearly useless (and also dangerous). So, do something like this:
config.setDirectoryForTemplateLoading(new File(
"C:/Users/Jay/workspace/WebService/templates"));
and then:
config.getTemplate("fibplain.xml");
Note that the /template
prefix is not there now, as the template path is relative to C:/Users/Jay/workspace/WebService/templates
. (This also means that the template can't back out of it with ../
-s, which can be important for security.)
Instead of loading from a real directory, you can also load templates from a SerlvetContext
, from the "class path", etc. It all depends on what TemplateLoader
you are choosing.
See also: http://freemarker.org/docs/pgui_config_templateloading.html
Update: If you get FileNotFoundException
instead of TemplateNotFoundException
, it's time to upgrade FreeMarker to at least 2.3.22. It also gives better error messages, like if you do the typical mistake of using the default TemplateLoader
, it tells you that right in the error message. Less wasted developer time.
You can solve this problem like that.
public class HelloWorldFreeMarkerStyle {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.setClassForTemplateLoading(HelloWorldFreeMarkerStyle.class, "/");
FileTemplateLoader templateLoader = new FileTemplateLoader(new File("resources"));
configuration.setTemplateLoader(templateLoader);
Template helloTemp= configuration.getTemplate("hello.ftl");
StringWriter writer = new StringWriter();
Map<String,Object> helloMap = new HashMap<String,Object>();
helloMap.put("name","gokhan");
helloTemp.process(helloMap,writer);
System.out.println(writer);
}
}