JAVA--文件内容属性替换
说明:文件中执行内容是变量,随着环境不同会配置不同,在程序启动后,读取配置进行变量替换
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; }
JAVA--文件内容属性替换的更多相关文章
- [ SHELL编程 ] 文件内容大小写替换
shell编程经常会碰到字符串.文件内容大小写的转换,在不同的场景下选择合适的命令可以提高编程效率. 适用场景 需大小写转换的文件内容或字符串 字符串大小写替换 小写替换大写 echo "h ...
- Advanced Find and Replace(文件内容搜索替换工具)v7.8.1简体中文破解版
Advanced Find and Replace是一款文件内容搜索工具,同时也是文件内容批量替换工具.支持通配符和正则表达式,方便快捷强大! 显示中文的方法:第二个菜单-Language-选 下载地 ...
- Shell实现文件内容批量替换的方法
在Linux系统中,文件内容的批量替换同Windows平台相比要麻烦一点.不过这里可以通过Shell命令或脚本的方式实现批量替换的功能. 笔者使用过两个命令:perl和sed ,接下来会对其做出说明. ...
- Java文件内容的复制
package a.ab; import java.io.*; public class FileReadWrite { public static void main(String[] args) ...
- Linux 查找文件内容、替换
有的时候我们经常性的需要在 linux 某一个目录下查找那些文件里包含我们需要查找的字符,那么这个时候就可以使用一些命令来查找,比如说 grep 1.grep 查询 1.1. 主要参数 [option ...
- linux递归查找文件内容并替换
sed -i 's/原字符串/替换后字符串/g' `grep '搜索关键字' -rl /data/目标目录/ --include "*.html"` 上面是递归查找目录中所有的HT ...
- python 文件内容修改替换操作
当我们读取文件中内容后,如果想要修改文件中的某一行或者某一个位置的内容,在python中是没有办法直接实现的,如果想要实现这样的操作只能先把文件所有的内容全部读取出来,然后进行匹配修改后写入到新的文件 ...
- linux 查找目录下的文件内容并替换(批量)
2.sed和grep配合 命令:sed -i s/yyyy/xxxx/g `grep yyyy -rl --include="*.txt" ./` 作用:将当前目录(包括子目录)中 ...
- Java文件内容读写
package regionForKeywords; import java.io.*; /** * Created by huangjiahong on 2016/2/25. */ public c ...
随机推荐
- Linux01——常用命令
帮助命令: man 一行一行显示 ,按下enter键就向下显示一行,按q退出 --help 全部显示 日期类:date ,cal 显示当前目录:pwd 切换目录:cd(***重点***) cd .. ...
- 01-Spring的概述
Spring概述 ①Spring是一个开源框架 ②Spring为简化企业级开发而生,使用Spring开发可以将Bean对象,Dao组件对象,Service组件对象等交给Spring容器来管理,这样使得 ...
- S3C2440_时钟和电源管理_阅读开发手册记录
1.如何进入sleep mode 1)要把一些重要的数据存放在状态寄存器里,状态寄存器里的数据在掉电后不会丢失. 2)要设置好唤醒源 3)配置相关寄存器,使其进入sleep mode 2.如何从sle ...
- 201771010135 杨蓉庆《面对对象程序设计(java)》第十八周学习总结
1.实验目的与要求 (1) 综合掌握java基本程序结构: (2) 综合掌握java面向对象程序设计特点: (3) 综合掌握java GUI 程序设计结构: (4) 综合掌握java多线程编程模型: ...
- 【C语言】输入一个年份和月份,输出该月的天数
分析: 三种类型, A.2月比较特殊,平年的2月只有28天,而闰年的2月有 29 天: B.4.6.9.11月: C.其他1.3.5.7.8.10.12月. 代码: /*输入一个年份和月份,输出该月的 ...
- P1028
一开始没看懂题,看了题解才明白的 = =.思路是,先找规律,会发现有重合部分,利用这些重合部分,写出递推公式. num = 0 时,只有 1 种组合: num = 1 时,只有 1 种组合: num ...
- JS-正则表达式常规运用
限制文本框只能输入0和正数 <input type="text" onkeyup="this.value=this.value.replace(/\D/g,'')& ...
- Python3.5学习之旅——day6
面向对象编程的学习 一.定义 首先跟大家介绍一位资深的程序员前辈说过的编程心得: 1.写重复代码是非常不好且低级的行为 2.完成的代码需要经常变更 所以根据以上两个心得,我们可以知道写的代码一定要遵循 ...
- Java后台技术IBATIS入门
做过.net后台开发的同志一定用过Entity FrameWork,该框架实现了实体Entity到数据库行的映射,通过操作实体DataSet,就能够直接同步修改到数据库.但是Java暂时没有类似的技术 ...
- python上传文件接口
1.由于公司做接口测试,遇到了上传文件,一直搞了好久,原来是加了头部的原因def test_79(self): '''导入配置文件''' request = e['mysqlshujuku'] url ...