Skip to content

Instantly share code, notes, and snippets.

@skanga
Last active February 21, 2019 17:43
Show Gist options
  • Save skanga/2e26e21490701596f6f3fcdce407a782 to your computer and use it in GitHub Desktop.
Save skanga/2e26e21490701596f6f3fcdce407a782 to your computer and use it in GitHub Desktop.
Simple string templates for java. The template can be in the code or in an external file, and any type of delimiters may be used for the variables. The data is provided in a HashMap.
import java.io.IOException;
import java.lang.StringBuilder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
public class StringTemplate
{
public static String templateReplace (String templateStr, String varStart, String varEnd, HashMap <String, String> paramValues)
{
StringBuilder resultBuilder = new StringBuilder ();
int paramLocation = 0;
int paramStart, paramEnd;
for (;;)
{
paramStart = templateStr.indexOf (varStart, paramLocation); // Look for the start of a variable
if (paramStart == -1) // Not found. Copy remaining data until template end and quit
{
resultBuilder.append (templateStr.substring (paramLocation, templateStr.length ()));
break;
}
paramEnd = templateStr.indexOf (varEnd, paramStart); // Look for the end of the variable
String varName = templateStr.substring (paramStart + varStart.length (), paramEnd); // Extract variable name
resultBuilder.append (templateStr.substring (paramLocation, paramStart)); // Add text preceding the variable
resultBuilder.append (paramValues.get (varName)); // Replace variable it's value from the map
paramLocation = paramEnd + varEnd.length (); // Set the current pointer location
}
return resultBuilder.toString ();
}
public static String readFile (String path, Charset encoding)
throws IOException
{
byte[] allBytes = Files.readAllBytes (Paths.get (path));
return new String (allBytes, encoding);
}
// Just for testing
public static void main (String[] args) throws IOException
{
// This is the data
HashMap <String, String> map = new HashMap <String, String> ();
map.put ("site", "Canada");
map.put ("user", "Dude");
map.put ("summary", "my title");
map.put ("description", "this is a description");
map.put ("assignee", "skanga");
// Try a template with variables in %(varName) format
System.out.println (templateReplace ("Hello %(user),\n\tWelcome to %(site).", "%(", ")", map));
// Try another template with variables in <<<varName>>> format
System.out.println (templateReplace ("Hello <<<assignee>>>,\n\tWelcome to <<<site>>>.", "<<<", ">>>", map));
// Try a template which is stored in an external file (json in this case) with variables in ${varName} format like bash
String fileContent = readFile ("template.json.txt", StandardCharsets.UTF_8);
System.out.println (templateReplace (fileContent, "${", "}", map));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment