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 ...
随机推荐
- 2020 安恒2月月赛 misc
题目链接:https://pan.baidu.com/s/19l54Nukt6evOr4UgbHMXIQ 提取码:1qbs 0x01 lemonEssence 咦?在kali打开是出错,改宽后图片变了 ...
- Kubernetes(k8s)完整安装教程
Kubernetes(k8s)完整安装教程 2019-08-27 2.3k 记录 发表评论 目录 1 安装 1.1 安装 Docker 1.2 安装 VirtualBox 1.3 安装 kubect ...
- 吴裕雄 python 人工智能——基于Mask_RCNN目标检测(1)
import os import sys import random import math import numpy as np import skimage.io import matplotli ...
- Sudo临时提权配置
目录 Sudo临时提权配置 参考 Sudo简介 Sudo配置文件 Sudo配置语法 Sudo配置实例 Sudo日志记录 Sudo临时提权配置
- webpack 中使用 autoprefixer
webpack中autoprefixer是配合postcss-loader使用的,首先安装相应资源: npm i -D style-loader css-loader postcss-loader a ...
- 解决安装 fireworks、photoshop 时卡在输入账号、手机号处等问题
一定要断网! 一定要断网! 一定要断网! 重要的事情说三遍! 我安装的是破解版CS6系列: 安装步骤如下: 1.当进行安装到此步时,(前面的步骤为解压文件等便不解释),选择“试用”,此时应该是 断网 ...
- 从头学pytorch(四) softmax回归实现
FashionMNIST数据集共70000个样本,60000个train,10000个test.共计10种类别. 通过如下方式下载. mnist_train = torchvision.dataset ...
- Qt应用程序的打包
Windows系统下打包: qt用realse版本编译然后打包发行 debug编译后的文件比realse版本大很多先在编译好的debug或者realse执行程序的目录下将执行该城西对应的所有dell文 ...
- git清除用户信息
remote: Repository not found. fatal: repository 'https://github.com/chenbowen950908/zhongzanjiaoyu.g ...
- 吴裕雄 python 神经网络——TensorFlow 队列操作
import tensorflow as tf q = tf.FIFOQueue(2, "int32") init = q.enqueue_many(([0, 10],)) x = ...