配置模板的生成

这篇博客介绍了如何使用配置模板生成配置信息,并在Java中实现字符串占位符的替换。通过读取配置文件,将占位符替换为实际值,然后生成新的配置文件。该过程涉及Apache Commons IO库,包括文件读写和字符串处理方法。
摘要由CSDN通过智能技术生成

使用配置模板生成配置信息

  1. 模板内容如下,需要替换其中的占位符信息,但是格式又不能改变

    spring:
    	server:
    		port: ${port}
    
    database:
    	url: ${url}
    	username: ${username}
    	password: ${password}
    
  2. 在pom文件中引用

    <dependency>
    	<groupId>commons-io</groupId>
    	<artifactId>commons-io</artifactId>
    	<version>2.2</version>
    </dependency>
    
  3. 替换字符串中的占位符的方法

    /**
     * 替换字符串中的占位符
     * @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;
    }
    
  4. 将配置文件变成字符串

    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("输入流变成字符串出错");
        }
    }
    
  5. 将以上两个方法组合起来就可以替换文件中的占位符了

    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("写入新文件失败");
        }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值