ConfigFileUtil.java 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package com.ruoyi.Common;
  2. import org.apache.commons.lang3.text.StrSubstitutor;
  3. import java.io.IOException;
  4. import java.nio.file.Files;
  5. import java.nio.file.Path;
  6. import java.nio.file.Paths;
  7. import java.util.Map;
  8. /**
  9. * @author zhengxiaohui
  10. * @date 2023/8/15 19:07
  11. * @desc 配置文件处理工具
  12. */
  13. public class ConfigFileUtil {
  14. /**
  15. * 获取请求数据报文内容
  16. * @param templateFilePath 报文模板格式文件位置,位于resources文件夹下面(conf/--/--.xx)
  17. * @param parameter 模板中可以替换的占位参数信息
  18. * @return
  19. */
  20. public static String getReqBodyFromTemplate(String templateFilePath, Map<String, Object> parameter) {
  21. String templateContent = ConfigFileUtil.readFileContent(templateFilePath);
  22. return ConfigFileUtil.replace(templateContent, parameter);
  23. }
  24. /**
  25. * 读取xml配置文件
  26. *
  27. * @param filePath 文件相对于resources文件夹的相对路径
  28. * @return
  29. */
  30. public static String readFileContent(String filePath) {
  31. String resourcePath = CommonMethod.getResFileAbsPath(filePath);
  32. // 读取指定文件路径的文件内容
  33. String contentStr = "";
  34. try {
  35. Path path = Paths.get(resourcePath);
  36. contentStr = new String(Files.readAllBytes(path));
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. }
  40. return contentStr;
  41. }
  42. /**
  43. * 替换 占位符变量固定为 ${}格式
  44. *
  45. * @param source 源内容
  46. * @param parameter 占位符参数
  47. * <p>
  48. * 转义符默认为'$'。如果这个字符放在一个变量引用之前,这个引用将被忽略,不会被替换 如$${a}将直接输出${a}
  49. * @return
  50. */
  51. public static String replace(String source, Map<String, Object> parameter) {
  52. return replace(source, parameter, "${", "}", false);
  53. }
  54. /**
  55. * 替换
  56. *
  57. * @param source 源内容
  58. * @param parameter 占位符参数
  59. * @param prefix 占位符前缀 例如:${
  60. * @param suffix 占位符后缀 例如:}
  61. * @param enableSubstitutionInVariables 是否在变量名称中进行替换 例如:${system-${版本}}
  62. * <p>
  63. * 转义符默认为'$'。如果这个字符放在一个变量引用之前,这个引用将被忽略,不会被替换 如$${a}将直接输出${a}
  64. * @return
  65. */
  66. public static String replace(String source, Map<String, Object> parameter, String prefix, String suffix, boolean enableSubstitutionInVariables) {
  67. //StrSubstitutor不是线程安全的类
  68. StrSubstitutor strSubstitutor = new StrSubstitutor(parameter, prefix, suffix);
  69. //是否在变量名称中进行替换
  70. strSubstitutor.setEnableSubstitutionInVariables(enableSubstitutionInVariables);
  71. return strSubstitutor.replace(source);
  72. }
  73. }