【推荐】工具类 : 输出有格式要求的 "字符串"

215 阅读1分钟

正文开始

分享一段我比较常用的模板填充工具代码,用于输出各种 [有格式要求的字符串]。

模板文件

image.png

参数组装

image.png

输出

image.png

实现

依赖

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.6</version>
</dependency>

工具类

package com.fast.util;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import lombok.NonNull;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author nano
 */
public class ClassPathFileUtils {

    /**
     * 读取文件信息
     *
     * @param path 资源文件路径
     * @return {@link String}
     */
    public static String readContent(String path) {
        ClassPathResource classPathResource = new ClassPathResource(path);
        return new BufferedReader(new InputStreamReader(classPathResource.getStream()))
                .lines()
                .parallel()
                .collect(Collectors.joining(System.lineSeparator()));
    }

    /**
     * 读取文件信息
     *
     * @param path 资源文件路径
     * @return {@link Reader}
     */
    public static Reader getReader(String path) {
        ClassPathResource classPathResource = new ClassPathResource(path);
        return new BufferedReader(new InputStreamReader(classPathResource.getStream()));
    }

    /**
     * 参数填充
     *
     * @param param    参数
     * @param filePath 文件位置
     * @return {@link String}
     */
    public static String fillParam(@NonNull JSONObject param, @NonNull String filePath) {
        String content = readContent(filePath);
        Assert.notBlank(content, ExcpUtils.get("file not exist or content is blank"));
        for (Map.Entry<String, Object> entry : param.getRaw().entrySet()) {
            String key = entry.getKey();
            String value = StrUtil.toStringOrNull(entry.getValue());
            content = content.replaceAll("\{" + key + "}", value);
        }
        return content;
    }

}

简单说下实现 就是给 传入参数的{key} -> 替换成value 别的没了

也不算啥优势

  • 无关动态参数顺序
  • 无关动态参数在模板中出现次数

应用场景

k8s pod 启动yaml

image.png

飞书机器人消息参数

image.png

生成可执行的shell脚本

image.png

简单举几个我常用的例子,朋友们可以继续扩展其他业务方向。下期再会。