说明:文件中执行内容是变量,随着环境不同会配置不同,在程序启动后,读取配置进行变量替换

1、测试类如下:

public class FileUtilsTest {

    //public static boolean fileAttributesReplace(String filePath,String propFilePath)
@org.junit.Test
public void testFileAttributesReplace() throws Exception { String filePath = FileUtils.getProjectAbsoluteRootPath() +"\\src\\main\\resources\\FileUtils\\test.yml"; String propFilePath = FileUtils.getProjectAbsoluteRootPath() +"\\src\\main\\resources\\FileUtils\\prop.properties"; System.out.println(FileUtils.fileAttributesReplace(filePath,propFilePath)); }
}

2、替换前文件分别内容分别是:

替换前文件内容:

1)test.yml

---
name: init
init:
#create ~
- type: ${key}
operate: create
tableName: {A}
columnFamily:
- name: cf
blocksize:
ttl:
#compression: SNAPPY
- name: cm
blocksize:
ttl:
#compression: SNAPPY
regionFilePath: {{ hdm_home_dir }}/init/traffic/conf/hbase/regions.txt

2)属性properties文件内容

prop.properties

key = testkey

A =sdklfkjslghjsjgslgfljsdgj

3)替换后文件内容:

test.yml

---
name: init
init:
#create ~
- type: testkey
operate: create
tableName: sdklfkjslghjsjgslgfljsdgj
columnFamily:
- name: cf
blocksize:
ttl:
#compression: SNAPPY
- name: cm
blocksize:
ttl:
#compression: SNAPPY
regionFilePath: {{ hdm_home_dir }}/init/traffic/conf/hbase/regions.txt

相关程序代码:

    /**
* 获取工程的根目录绝对路径,“D:\workdir\HWF”
*
* @return
*/
public static String getProjectAbsoluteRootPath() { return System.getProperty("user.dir"); }
 /**
* filePath文件中的属性用propFilePath文件中具有相同key的value值替换
* @param filePath 为需要替换属性的文件路径
* @param propFilePath properties文件路径
* @return 是否wan全部替换成功
*/
public static boolean fileAttributesReplace(String filePath,String propFilePath){ if(org.apache.commons.lang.StringUtils.isEmpty(filePath) || org.apache.commons.lang.StringUtils.isEmpty(propFilePath) ){ LOG.error("filePath = {} or propFilePath = {} is empty",filePath,propFilePath); return false;
} if(!new File(filePath).exists() || !new File(propFilePath).exists()){ LOG.error("filePath = {} or propFilePath = {} 不存在",filePath,propFilePath); return false;
} //把文件内容全部读取到List中,然后做属性替换,替换完成后,重新写文件
List<String> list = readFileToList(filePath); Map<String,String> map = readPropFileToMap(propFilePath); List<String> result = attributesReplace(list,map); return writeListToFile(result,filePath); } /**
* 属性替换
* @param list
* @param map
* @return
*/
public static List<String> attributesReplace(List<String> list, Map<String,String> map){ if(list.size() < || map.size() < ){ return list;
} List<String> result = new ArrayList<>(); //生成匹配模式的正则表达式
String patternString = "\\$\\{(" + org.apache.commons.lang.StringUtils.join(map.keySet(), "|") + ")\\}"; Pattern pattern = Pattern.compile(patternString); for (String template : list) { Matcher matcher = pattern.matcher(template); //两个方法:appendReplacement, appendTail
StringBuffer sb = new StringBuffer(); while(matcher.find()) { matcher.appendReplacement(sb, map.get(matcher.group()));
} matcher.appendTail(sb); result.add(sb.toString()); }
return result;
} /**
* 把list内容写入到文件中
* @param list
* @param filePath
* @return
*/
public static boolean writeListToFile(List<String> list,String filePath){ BufferedWriter writer = null; try { if(new File(filePath).exists()){ if(!new File(filePath).delete()){ LOG.error("删除文件:{}失败", filePath);
}
} writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), UTF8_CHARSET)); for (String temp : list) { writer.write(temp + "\n"); } writer.flush(); return true; } catch (IOException e) { LOG.error("写文件:{} 出现IO异常,异常信息:{}",filePath,e.getMessage()); return false; }finally { if(null != writer){ try { writer.close(); } catch (IOException e) { LOG.error("文件:{},关闭文件流时发生异常:{}", filePath, e.getMessage()); }
}
}
} /**
* 读取文件内容放到List
* @param filePath
* @return
*/
public static List<String> readFileToList(String filePath){ if(org.apache.commons.lang.StringUtils.isEmpty(filePath)){ LOG.error("filePath = {} is empty",filePath); return new ArrayList<>();
} if(!new File(filePath).exists() ){ LOG.error("filePath = {} 不存在",filePath); return new ArrayList<>();
} BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)), UTF8_CHARSET)); String tempString; List<String> list = new ArrayList<>(); while ((tempString = reader.readLine()) != null) { list.add(tempString); } return list; } catch (FileNotFoundException e){ LOG.error("filePath = {} 不存在",filePath); return new ArrayList<>(); }catch (IOException e){ LOG.error("读取filePath = {} 文件发生异常,异常信息:{}",filePath,e.getMessage()); return new ArrayList<>(); }finally{ if ( null != reader ) { try { reader.close(); } catch (IOException e) { LOG.error("文件:{},关闭文件流时发生异常:{}", filePath, e.getMessage()); }
}
} } /**
* 拷贝src文件成dst文件
* @param src
* @param dst
* @return
*/
public static boolean copy(String src,String dst){ BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(src), UTF8_CHARSET)); String temp; writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst, true), UTF8_CHARSET)); while ((temp = reader.readLine()) != null) { writer.write(temp + "\n"); } writer.flush(); LOG.info("复制文件从src ={} 到dst = {} 成功", src, dst); return true; } catch (IOException e) { LOG.error("复制文件从src ={} 到dst = {} 出现IO异常,error:{}",src,dst,StringUtils.getMsgFromException(e)); return false; }finally { if(null != reader){ try { reader.close(); } catch (IOException e) { LOG.error("文件:{},关闭文件流时发生异常:{}", src, e.getMessage());
}
} if(null != writer){ try { writer.close(); } catch (IOException e) { LOG.error("文件:{},关闭文件流时发生异常:{}", dst, e.getMessage());
}
}
} } /**
* 读取properties文件内容转成map
* @param propFilePath properties文件路径
* @return map
*/
public static Map<String,String> readPropFileToMap(String propFilePath){ Map<String, String> map = new HashMap<>(); if(org.apache.commons.lang.StringUtils.isEmpty(propFilePath)){ LOG.error("propFilePath = {} is empty",propFilePath); return map;
} File propFile = new File(propFilePath); if(!propFile.exists()){ LOG.error("propFilePath = {} 不存在",propFilePath); return map;
} Properties prop = new Properties(); try { prop.load(new BufferedReader(new InputStreamReader(new FileInputStream(propFile), Charset.forName(Constants.UTF8)))); } catch (FileNotFoundException e){ LOG.error("propFilePath = {} 不存在",propFilePath); return map; } catch(IOException e) { LOG.error("加载propFilePath = {} 文件出现异常,异常信息:{}" ,propFilePath,e.getMessage()); return map;
} for (Map.Entry<Object, Object> entry : prop.entrySet()) { map.put(((String)entry.getKey()).trim(),((String)entry.getValue()).trim());
} return map; }

最新文章

  1. MSSQL数据库的一些基础知识
  2. UI设计中px、pt、ppi、dpi、dp、sp之间的关系
  3. php二维数组排序的处理
  4. Android布局_布局概述和LinearLayout布局
  5. win10下安装centOS 7 U盘
  6. sqlsevrer中output的用法
  7. ac automaton 专题
  8. 学习ReactNative笔记整理一___JavaScript基础
  9. php curl详解用法[真的详解]
  10. applet授权数字签名
  11. iOS开发之NSObject的多线程
  12. javaSE_07Java中类和对象-封装特性-思维导图
  13. Orleans稍微复杂的例子—互动
  14. android支付宝app支付(原生态)-包括android前端与java后台
  15. 1290 - The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
  16. Common-used commands in Docker
  17. Oracle Gateways 方式创建dblink 连接 SQLSERVER数据库
  18. 【洛谷P1463】反素数
  19. 转:vue+canvas如何实现b站萌系登录界面
  20. OO作业总结报告3

热门文章

  1. Plastic Bottle Manufacturer Profile: Plastic Bottle Forming Process
  2. shell脚本编程学习笔记(三)编写邮件报警脚本
  3. JAVA基础学习(5)之数组
  4. Python(三)enumerate函数
  5. 【PAT甲级】1078 Hashing (25 分)(哈希表二次探测法)
  6. 怎么拆分一个Excel工作簿中的多个工作表?
  7. Redis搭建一主一从及哨兵模式(二)
  8. 「CF859E」Desk Disorder
  9. C#中equals和==的区别有哪些
  10. linux克隆多台虚拟机后网络无法识别更无法连接上网的解决方法