spring-bootfreemarkervelocityjava-17

Best templating engine to generate files with dynamic content from Spring Boot application


I have a requirement of generating text files with some dynamic content. Like I will generate some content like "Hello <>, how are you?", where name would be dynamic. My application is a Spring Boot 2.x application. I went through most of the tutorials of Apache Velocity and Apache Freemarker, but all the tutorials says about generating HTML or XML files. Can you please guide me which framework would be best for generating other file types like text file and give hint for getting started with that from Spring Boot application?


Solution

  • What is stopping you from using velocity template to generate txt file

    template.vm

    "Hello  $name, how are you?"
    

    Java code

    import org.apache.velocity.VelocityContext;
    import org.apache.velocity.app.Velocity;
    
    import java.io.FileWriter;
    import java.io.Writer;
    
    public class VelocityTextFileGenerator {
        public static void main(String[] args) {
            try {
                Velocity.init();
    
                VelocityContext context = new VelocityContext();
                context.put("name", "My name");
    
                String templateFile = "template.vm";
                String outputFile = "output.txt";
    
                Writer writer = new FileWriter(outputFile);
    
                
                Velocity.mergeTemplate(templateFile, "UTF-8", context, writer);
    
                writer.close();
    
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }