博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java占位符替换工具类
阅读量:4539 次
发布时间:2019-06-08

本文共 2691 字,大约阅读时间需要 8 分钟。

import java.util.HashMap;      import java.util.Map;            import org.slf4j.Logger;      import org.slf4j.LoggerFactory;            /**      * 配置文件或模板中的占位符替换工具类      * Date: 15-5-8      * Time: 下午4:12      */      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 system property placeholders: "}"          */          public static final String PLACEHOLDER_SUFFIX = "}";                public static String resolvePlaceholders(String text, Map
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("Could not resolve placeholder '" + placeholder + "' in [" + text + "] "); } } catch (Exception ex) { logger.warn("Could not resolve placeholder '" + placeholder + "' in [" + text + "]: " + ex); } startIndex = buf.indexOf(PLACEHOLDER_PREFIX, nextIndex); } else { startIndex = -1; } } return buf.toString(); } public static void main(String[] args) { String aa= "我们都是好孩子,${num}说是嘛? 我觉得${people}是傻蛋!"; Map
map = new HashMap
(); map.put("num","小二比"); map.put("people","小明"); System.out.println(PlaceholderUtils.resolvePlaceholders(aa, map)); } }

  

转载于:https://www.cnblogs.com/toSeeMyDream/p/6814430.html

你可能感兴趣的文章
java基础篇---网络编程(UDP程序设计)
查看>>
Kafka Producer相关代码分析【转】
查看>>
麻省理工学院公开课-第四讲:快速排序 及 随机化 算法
查看>>
pycharm 的包路径设置export PYTHONPATH=$PYTHONPATH
查看>>
SQL语句创建函数
查看>>
解决mysql无法显示中文/MySQL中文乱码问号等问题
查看>>
CentOS 7.2 配置mysql5.7
查看>>
python输出转义字符
查看>>
计算一个整数二进制中1的个数
查看>>
netdom join 错误:指定的域不存在,或无法联系。
查看>>
Android中Dialog的使用
查看>>
Android Activity接收Service发送的广播
查看>>
[Leetcode] Spiral Matrix | 把一个2D matrix用螺旋方式打印
查看>>
加速和监控国际网络
查看>>
【Flex】读取本地XML,然后XML数据转成JSON数据
查看>>
字符串循环右移-c语言
查看>>
解决从pl/sql查看oracle的number(19)类型数据为科学计数法的有关问题
查看>>
古训《增广贤文》
查看>>
职场的真相——七句话
查看>>
xcode命令行编译时:codesign命令,抛出“User interaction is not allowed.”异常 的处理...
查看>>