Recently I got a situation to create 20 similar type of HTML files which differs in only content. Then I got this idea make this automate. Here you can find Java program which is able to create HTML files based on a template.

Make your template ready

Here in template you can observe the title, body tags. These elements have template words title and message. These were specified in ${...} for easy replacement
<html>
  <head>
    <title>${title}</title>
  </head>
  <body>
    ${message}
  </body>
</html>

Get TemplateMatcher

To use TemplateMatcher, you need to have jlibs-core jar in build-path. You can download this jar from https://code.google.com/p/jlibs/downloads/list. Read more about TemplateMatcher at http://blog.sodhanalibrary.com/2014/09/format-html-styled-email-using-java.html

Java Code

Algorithm of this below program is very simple.
  1. Read template file content
  2. Replace template words with new words
  3. Write the generated content into new file
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import jlibs.core.util.regex.TemplateMatcher;

public class TemplateFiles {
    
   
   static public String getContents(File aFile) {
        //...checks on aFile are elided
        StringBuilder contents = new StringBuilder();
        
        try {
          //use buffering, reading one line at a time
          //FileReader always assumes default encoding is OK!
          BufferedReader input =  new BufferedReader(new FileReader(aFile));
          try {
            String line = null; //not declared within while loop
            /*
            * readLine is a bit quirky :
            * it returns the content of a line MINUS the newline.
            * it returns null only for the END of the stream.
            * it returns an empty String if two newlines appear in a row.
            */
            while (( line = input.readLine()) != null){
              contents.append(line);
              contents.append(System.getProperty("line.separator"));
            }
          }
          finally {
            input.close();
          }
        }
        catch (IOException ex){
          ex.printStackTrace();
        }
        
        return contents.toString();
      }

      /**
      * Change the contents of text file in its entirety, overwriting any
      * existing text.
      *
      * This style of implementation throws all exceptions to the caller.
      *
      * @param aFile is an existing file which can be written to.
      * @throws IllegalArgumentException if param does not comply.
      * @throws FileNotFoundException if the file does not exist.
      * @throws IOException if problem encountered during write.
      */
      static public void setContents(File aFile, String aContents)
                                     throws FileNotFoundException, IOException {
        if (aFile == null) {
          throw new IllegalArgumentException("File should not be null.");
        }
        if (!aFile.exists()) {
            aFile.createNewFile();
        }
        if (!aFile.isFile()) {
          throw new IllegalArgumentException("Should not be a directory: " + aFile);
        }
        if (!aFile.canWrite()) {
          throw new IllegalArgumentException("File cannot be written: " + aFile);
        }
        

        //use buffering
        Writer output = new BufferedWriter(new FileWriter(aFile));
        try {
          //FileWriter always assumes default encoding is OK!
          output.write( aContents );
        }
        finally {
          output.close();
        }
      }

      /** Simple test harness.   */
      public static void main (String args[]) throws IOException {
        
        // template file
        File templateFile = new File("C:\\template.html");
        // file to be created
        File distFile = new File("C:\\template1.html"); 
        
        // get content of template file
        String template = getContents(templateFile);
       
        // set template fields 
        Map<String, String> vars = new HashMap<String, String>();
        vars.put("title", "srinivas");
        vars.put("body", "21");

        // Match and replace template words     
        TemplateMatcher matcher = new TemplateMatcher("${", "}");
        setContents(distFile, matcher.replace(template, vars));
      }
   
}

0 comments:

Blogroll

Follow this blog by Email

Popular Posts