Search code examples
javafreemarkerfilenotfoundexception

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!


Solution

  • 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.