JAVA--⽂件内容属性替换说明:⽂件中执⾏内容是变量,随着环境不同会配置不同,在程序启动后,读取配置进⾏变量替换1、测试类如下:
public class FileUtilsTest {
//public static boolean fileAttributesReplace(String filePath,String propFilePath)
@org.junit.Test
public void testFileAttributesReplace() throws Exception {
String filePath = ProjectAbsoluteRootPath() +"\\src\\main\\resources\\FileUtils\\l";
String propFilePath = ProjectAbsoluteRootPath() +"\\src\\main\\resources\\FileUtils\\prop.properties";        System.out.println(FileUtils.fileAttributesReplace(filePath,propFilePath));
}
}
2、替换前⽂件分别内容分别是:
替换前⽂件内容:
1)l
---
name: init
init:
#create 1~5
- type: ${key}
operate: create
tableName: {A}
columnFamily:
-
name: cf
blocksize: 1048576
ttl: 94867200
#compression: SNAPPY
- name: cm
blocksize: 1048576
ttl: 94867200
#compression: SNAPPY
regionFilePath: {{ hdm_home_dir }}/init/traffic/conf/
2)属性properties⽂件内容
prop.properties
key = testkey
A =sdklfkjslghjsjgslgfljsdgj
3)替换后⽂件内容:
---
name: init
init:
#create 1~5
- type: testkey
operate: create
tableName: sdklfkjslghjsjgslgfljsdgj
columnFamily:
- name: cf
blocksize: 1048576
ttl: 94867200
#compression: SNAPPY
- name: cm
blocksize: 1048576
ttl: 94867200
#compression: SNAPPY
regionFilePath: {{ hdm_home_dir }}/init/traffic/conf/
相关程序代码:
/
**
* 获取⼯程的根⽬录绝对路径,“D:\workdir\HWF”
*
* @return
*/
public static String getProjectAbsoluteRootPath() {
Property("user.dir");
}
/**
* filePath⽂件中的属性⽤propFilePath⽂件中具有相同key的value值替换
* @param filePath 为需要替换属性的⽂件路径
* @param propFilePath properties⽂件路径
* @return 是否wan全部替换成功
*/
public static boolean fileAttributesReplace(String filePath,String propFilePath){
if(org.apachemons.lang.StringUtils.isEmpty(filePath) || org.apachemons.lang.StringUtils.isEmpty(propFilePath) ){            ("filePath = {} or propFilePath = {} is empty",filePath,propFilePath);
return false;
}
if(!new File(filePath).exists() || !new File(propFilePath).exists()){
<("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() < 1 || map.size() < 1){
return list;
}
List<String> result = new ArrayList<>();
//⽣成匹配模式的正则表达式
String patternString = "\\$\\{(" + org.apachemons.lang.StringUtils.join(map.keySet(), "|") + ")\\}";
Pattern pattern = Patternpile(patternString);
for (String template : list) {
Matcher matcher = pattern.matcher(template);
//两个⽅法:appendReplacement, appendTail
StringBuffer sb = new StringBuffer();
while(matcher.find()) {
matcher.appendReplacement(sb, (up(1)));
}
matcher.appendTail(sb);
result.String());
}
return result;
}
/
**
* 把list内容写⼊到⽂件中
* @param list
* @param filePath
* @return
*/
public static boolean writeListToFile(List<String> list,String filePath){
java replace方法
BufferedWriter writer = null;
try {
if(new File(filePath).exists()){
if(!new File(filePath).delete()){
<("删除⽂件:{}失败", 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) {
<("写⽂件:{} 出现IO异常,异常信息:{}",Message());
return false;
}finally {
if(null != writer){
try {
writer.close();
} catch (IOException e) {
<("⽂件:{},关闭⽂件流时发⽣异常:{}", filePath, e.getMessage());
}
}
}
}
/
**
* 读取⽂件内容放到List
* @param filePath
* @return
*/
public static List<String> readFileToList(String filePath){
if(org.apachemons.lang.StringUtils.isEmpty(filePath)){
<("filePath = {} is empty",filePath);
return new ArrayList<>();
}
if(!new File(filePath).exists() ){
<("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 = adLine()) != null) {
list.add(tempString);
}
return list;
} catch (FileNotFoundException e){
<("filePath = {} 不存在",filePath);
return new ArrayList<>();
}catch (IOException e){
<("读取filePath = {} ⽂件发⽣异常,异常信息:{}",Message());
return new ArrayList<>();
}finally{
if ( null != reader ) {
try {
reader.close();
} catch (IOException e) {
<("⽂件:{},关闭⽂件流时发⽣异常:{}", 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 = adLine()) != null) {
writer.write(temp + "\n");
}
writer.flush();
LOG.info("复制⽂件从src ={} 到dst = {} 成功", src, dst);
return true;
} catch (IOException e) {
<("复制⽂件从src ={} 到dst = {} 出现IO异常,error:{}",src,MsgFromException(e));
return false;
}finally {
if(null != reader){
try {
reader.close();
} catch (IOException e) {
<("⽂件:{},关闭⽂件流时发⽣异常:{}", src, e.getMessage());
}
}
if(null != writer){
try {
writer.close();
} catch (IOException e) {
<("⽂件:{},关闭⽂件流时发⽣异常:{}", 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.apachemons.lang.StringUtils.isEmpty(propFilePath)){
<("propFilePath = {} is empty",propFilePath);
return map;
}
File propFile = new File(propFilePath);
if(!ists()){
<("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){
<("propFilePath = {} 不存在",propFilePath);
return map;
} catch(IOException e) {
<("加载propFilePath = {} ⽂件出现异常,异常信息:{}" ,Message());
return map;
}
for (Map.Entry<Object, Object> entry : Set()) {
map.put(((Key()).trim(),((Value()).trim());

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。