使用Java替换字符串占位符的几种方法

使用Java替换字符串占位符的几种方法,第1张

import org.apache.commons.lang.text.StrSubstitutor;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

public class Test {
    public static void main(String[] args) {
   		//方法一
		String url = "jdbc:mysql://{ip}:{port}/{tenantCode}?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
       String context = url.replace("{ip}", "127.0.0.1").replace("{port}", "3306").replace("{tenantCode}", "test001");

        System.out.println(context);

		//方法二
        String url1 = "jdbc:mysql://%s:%s/%s?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
        String context1 = String.format(url1, "127.0.0.1", "3306", "test001");

        System.out.println(context1);

		//方法三
        String url2 = "jdbc:mysql://{0}:{1}/{2}?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
        String context2 = MessageFormat.format(url2, "127.0.0.1", "3306", "test001");

        System.out.println(context2);

		//方法四-需要引用commons-lang3或commons-text包
        Map map = new HashMap<>();
        map.put("ip", "127.0.0.1");
        map.put("port", "3306");
        map.put("tenantCode", "test001");
		
        StrSubstitutor strSubstitutor = new StrSubstitutor(map);
        String url3 = "jdbc:mysql://${ip}:${port}/${tenantCode}?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
        String context3 = strSubstitutor.replace(url3);
        System.out.println(context3);
    }
}

结果

jdbc:mysql://127.0.0.1:3306/test001?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai
jdbc:mysql://127.0.0.1:3306/test001?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai
jdbc:mysql://127.0.0.1:3306/test001?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai
jdbc:mysql://127.0.0.1:3306/test001?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/991766.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存