The placeholder replacement tool class in the configuration file or template, and the template tool class
Sometimes, a lot of text is stored in a database or file, and some variables or templates may have placeholders. However, each read, strings are removed one by one. replace replacement is very troublesome, so a placeholder replacement tool class is written.
Code:
Import java. util. hashMap; import java. util. map; import org. slf4j. logger; import org. slf4j. loggerFactory;/*** Replace the tool class with a placeholder in the configuration file or template * Date: 15-5-8 * Time: */public class PlaceholderUtils {private static final Logger logger = LoggerFactory. getLogger (PlaceholderUtils. class);/*** Prefix for system property placeholders: "$ {" */public static final String PLACEHOLDER_PREFIX = "$ {";/*** Suffix for syst Em property placeholders: "}" */public static final String PLACEHOLDER_SUFFIX = "}"; public static String resolvePlaceholders (String text, Map <String, String> parameter) {if (parameter = null | parameter. isEmpty () {return text;} StringBuffer buf = new StringBuffer (text); int startIndex = buf. indexOf (PLACEHOLDER_PREFIX); while (startIndex! =-1) {int endIndex = buf. indexOf (PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PREFIX.length (); if (endIndex! =-1) {String placeholder = buf. substring (startIndex + PLACEHOLDER_PREFIX.length (), endIndex); int nextIndex = endIndex + PLACEHOLDER_SUFFIX.length (); try {String propVal = parameter. get (placeholder); if (propVal! = Null) {buf. replace (startIndex, endIndex + PLACEHOLDER_SUFFIX.length (), propVal); nextIndex = startIndex + propVal. length ();} else {logger. warn ("cocould not resolve placeholder '" + placeholder + "' in [" + text + "]") ;}} catch (Exception ex) {logger. warn ("cocould not resolve placeholder '" + placeholder + "' in [" + text + "]:" + ex);} startIndex = buf. indexOf (PLACEHOLDER_PREFIX, nextIndex);} else {s TartIndex =-1 ;}} return buf. toString ();} public static void main (String [] args) {String aa = "we are all good children, $ {num} said yes? I think $ {people} is dumb! "; Map <String, String> map = new HashMap <String, String> (); map. put ("num", ""); map. put ("people", "James"); System. out. println (PlaceholderUtils. resolvePlaceholders (aa, map ));}}
Output result:
We are all good children. What do we mean by Xiaoer? I think James is dumb.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.