Java 生成 yaml (velocity)

依赖:

<!-- velocity -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
          </dependency>

工具类:

package com.yunphant.iie.utils;

import com.yunphant.iie.networkSimulation.dto.NetworkYamlDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;



@Slf4j
public class YamlUtils {


    /**
     * 根据文件路径读取文件内容
     * @param filePath
     * @return
     */
    public static String readFile(String filePath) {
        StringBuilder result = new StringBuilder();
        try {
//          BufferedReader bfr = new BufferedReader(new FileReader(new File(filePath)));
            BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)), "UTF-8"));
            String lineTxt = null;
            while ((lineTxt = bfr.readLine()) != null) {
                result.append(lineTxt).append("\n");
            }
            bfr.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }


    /**
     * 创建 Network yaml
     * @param dto  模版所需实体类
     * @param templatePath  模版路径
     * @param saveFliePath  模版保存路径
     * @return
     */
    public static Map<String,Object> creatyNetworkYaml(NetworkYamlDTO dto, String templatePath,String saveFliePath) {
        //初始化配置
        Template template = getVelocityEngine(templatePath);
        //定义替换规则
        VelocityContext context = new VelocityContext();
        Map<String, Object> stringObjectMap = EntityMapTransUtils.entityToMap1(dto);
        for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {
            if (Objects.nonNull(entry.getValue())){
                context.put(entry.getKey(),entry.getValue());
            }
        }
        //存储合并后的结果
        StringWriter sw = new StringWriter();
        template.merge(context,sw);
        Path savePath = Paths.get(saveFliePath, dto.getPumbaName() + ".yaml");
        File createFilePath = new File(savePath.toUri());
        try {
            String filePath = writeTemplateToNewFile(createFilePath, sw);
            log.info("文件存储路径:{}",filePath);
            String r = sw.toString();
//            log.info("##r:   \n" +r);
            HashMap<String, Object> map = new HashMap<>();
            map.put("filePath",filePath);
            map.put("script",r);
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }




    /**
     * 创建模版文件 返回文件路径
     * @param createFilePath
     * @param assignedValueTemplate
     * @return
     * @throws IOException
     */
    private static String writeTemplateToNewFile(File createFilePath, StringWriter assignedValueTemplate) throws IOException {
        FileWriter fileWriter = new FileWriter(createFilePath);
        fileWriter.append(assignedValueTemplate.toString());
        fileWriter.flush();
        fileWriter.close();
        return createFilePath.getAbsolutePath();

    }

    /**
     * 初始化 模版配置
     * @return
     */
    private static Template getVelocityEngine(String templatePath) {
        Properties props = new Properties();
        props.setProperty(Velocity.ENCODING_DEFAULT, "GBK");//全局编码,如果以下编码不设置它就生效
        props.setProperty(Velocity.INPUT_ENCODING, "UTF-8");//输入流的编码,其实是打酱油!非模板文件编码
        props.setProperty(Velocity.OUTPUT_ENCODING, "GBK");//输入流编码,很关键!
        props.setProperty(VelocityEngine.RESOURCE_LOADER,"file");//模板文件加载方式
        VelocityEngine ve = new VelocityEngine(props);
        //设置资源路径
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        //初始化
        ve.init();
        return ve.getTemplate(templatePath);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值