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 ...
随机推荐
- IIS反向代理配置教程(最终完整版本)
IIS代理配置教程 插件下载:https://download.csdn.net/download/song_yan_/11996489 一.安装反向代理插件 1.rewrite插件安装 (1) 双击 ...
- 位运算(&、|、^、~、>>、<<)
1.位运算概述 从现代计算机中所有的数据二进制的形式存储在设备中.即0.1两种状态,计算机对二进制数据进行的运算(+.-.*./)都是叫位运算,即将符号位共同参与运算的运算. 口说无凭,举一个简单的例 ...
- 正则去掉 html标签
var htmlStr='<p class="cjk" style="margin-bottom: 0cm; line-height: 16px;"> ...
- C语言:使用递归解决汉诺塔问题。
//汉诺塔:汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具.大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照大小顺序摞着64片黄金圆盘.大梵天命令婆罗门把圆盘从下面开始按大小 ...
- java比较时间的方法
一.通过compareTo Date date = new Date(1576118709574L); Date date1 = new Date(1576118709574L); Date date ...
- 关于idea2019.2.3版本中文控制台乱码问题
出现乱码后根据网上找的方法全都试过后还是显示乱码 更改VM Options为 -Dfile.encoding=UTF-8 添加备选字体 更改这两个文件 更改编码格式 以上这些方法全部设置 ...
- selenium+python+unittest实现自动化测试(入门篇)
本文主要讲解关于selenium自动化测试框架的入门知识点,教大家如何搭建selenium自动化测试环境,如何用selenium+python+unittest实现web页面的自动化测试,先来看看se ...
- vs的一些操作技巧:在写代码时自动换行的设置
有时在写代码的时候,一行代码太长了,想换行,直接按回车键的话又会报错,怎么办?其实可以这样设置vs,就可以达到自动换行的效果啦.
- linux的数据盘挂载
图文教程: Linux的云服务器数据盘未做分区和格式化,可以根据以下步骤进行分区以及格式化操作. 一:登陆 用Linux 的SSH 登陆软件(xshell 或者putty) 登陆阿里云主机服务器. 二 ...
- pytorch资料
torchvision是独立于pytorch的关于图像操作的一些方便工具库. torchvision的详细介绍在:https://pypi.org/project/torchvision/ torch ...