使用Java替换字符串占位符的几种方法
https://blog.csdn.net/m0_67402125/article/details/125383655
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);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
结果
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
- 1
- 2
- 3
- 4