使用配置模板生成配置信息
-
模板内容如下,需要替换其中的占位符信息,但是格式又不能改变
spring: server: port: ${port} database: url: ${url} username: ${username} password: ${password}
-
在pom文件中引用
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.2</version> </dependency>
-
替换字符串中的占位符的方法
/** * 替换字符串中的占位符 * @param config 字符串 * @param configMap 配置信息的map * @return */ public String replacePlaceHolder(String config, Map<String, String> configMap) { String result = config; //遍历map for (Map.Entry<String, String> entry : configMap.entrySet()) { //占位符 String placeHolder = "${" + entry.getKey() + "}"; //全部替换 result = result.replace(placeHolder, entry.getValue()); } return result; }
-
将配置文件变成字符串
import org.apache.commons.io.IOUtils; /** * 读取配置文件内容,变成字符串 * @param path 配置文件路径 * @return */ public String readConfigFileToString(String path) { File file = new File(path); if (!file.exists()) { throw new RuntimeException("文件不存在"); } //将文件变成输入流 try(FileInputStream is = new FileInputStream(file)) { //将输入流的内容变成字符串 String config = IOUtils.toString(is, "UTF-8"); return config; } catch (Exception e) { throw new RuntimeException("输入流变成字符串出错"); } }
-
将以上两个方法组合起来就可以替换文件中的占位符了
import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; /** * 生成新文件 * @param configPath 配置文件路径 * @param map 配置文件信息 * @param newPath 生成的新文件 */ public void generateConfigFile(String configPath, Map<String, String> map, String newPath) { File newFile = new File(newPath); //将配置文件变成字符串 String str = readConfigFileToString(configPath); //替换其中的占位符 String newConfigStr = replacePlaceHolder(str, map); try { //写入新文件 FileUtils.writeStringToFile(newFile, newConfigStr, "UTF-8"); } catch (IOException e) { throw new RuntimeException("写入新文件失败"); } }