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 ...
随机推荐
- 解密国内BAT等大厂前端技术体系-美团点评之上篇(长文建议收藏)
引言 进入2019年,大前端技术生态似乎进入到了一个相对稳定的环境,React在2013年发布至今已经6年时间了,Vue 1.0在2015年发布,至今也有4年时间了. 整个业界在前端框架不断迭代中,也 ...
- java中路径的问题
在java中,涉及路径的问题有很多,不管在windows还是linux系统中,不要纠结”/“分隔符的使用,在windows系统中,资源加载器会自动的将”/“转换成”\“. 在java中获取资源的方式有 ...
- java 面试题 高阶版
1.hash 算法问题 hash(n) /服务器个数 hash 算法在服务器增加或者减少的时候,数据存取位置为发生变化: 什么是一致性hash算法? 一致性hash算法对2^32 取模,整个Hash空 ...
- HITCON-Training-master 部分 Writeup(1月30更新)
0x01.lab3 首先checksec一下,发现连NX保护都没开,结合题目提示ret2sc,确定可以使用shellcode得到权限. IDA查看伪代码 大致分析: 将shellcode写入name数 ...
- 解决linux 运行自动化脚本浏览器无法启动问题
1.前提你的驱动和版本对应无问题时,依旧报未知错误无法启动chrome 解决方法加上两行: options.addArguments("no-sandbox");options.a ...
- SVM的优缺点
优点 可用于线性/非线性分类,也可以用于回归,泛化错误率低,也就是说具有良好的学习能力,且学到的结果具有很好的推广性. 可以解决小样本情况下的机器学习问题,可以解决高维问题,可以避免神经网络结构选择和 ...
- FastDFS上传文件访问url地址直接下载
fdfs 存储节点storage安装nginx,修改nginx配置文件 location ~/group[1-9]/M00 { if ( $query_string ~* ^(.*)paramete ...
- springboot pom问题及注解
springboot pom不需要指定版本号 springboot会自己管理版本号 <!-- 支持热部署 --> <dependency> <groupId>org ...
- 虚拟交换系统-VSS
1.虚拟交换系统VSS技术概述 VSS的特点: VSS将两台Catalyst 6500/4500系列交换机组合为单一虚拟交换机,对外来看,只有一台交换机,管理冗余链路如同管理自己的一个单一接口. VS ...
- 【原】Django常用命令总结
1.终端命令 # 查看django版本 $ python -m django --version # 创建项目,名为mysite $ django-admin startproject mysite ...