Thursday, December 25, 2014

Writing an HTML file from a template using Java

Create a template and save as template.html .
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>[TITLE]</title></head><body>[BODY]</body></html>
Put a tag like [TAG] for any dynamic content and then do something like this:
File htmlTemplateFile = new File("path/template.html");String htmlString = FileUtils.readFileToString(htmlTemplateFile);String title = "New Page";String body = "This is Body";htmlString = htmlString.replace("[TITLE]", title);htmlString = htmlString.replace("[BODY]", body);File newHtmlFile = new File("path/new.html");FileUtils.writeStringToFile(newHtmlFile, htmlString);

Note: You will need to import org.apache.commons.io.FileUtils to do this.

No comments:

Post a Comment