zoukankan      html  css  js  c++  java
  • 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 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/hbase/regions.txt

    2)属性properties文件内容

    prop.properties

    key = testkey
    
    A =sdklfkjslghjsjgslgfljsdgj

    3)替换后文件内容:

    test.yml

    ---
    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/hbase/regions.txt

    相关程序代码:

        /**
         * 获取工程的根目录绝对路径,“D:workdirHWF”
         *
         * @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() < 1 || map.size() < 1){
    
                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(1)));
                }
    
                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 + "
    ");
    
                }
    
                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 + "
    ");
    
                }
    
                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;
    
        }
  • 相关阅读:
    WinForm微信扫码登录
    php字符串只替换一次
    laravel6 文档
    MYSQL批量修改
    semanage command not found
    SUID、SGID、SBIT
    passwd命令
    redhat配置yum软件仓库
    mount: no medium found on /dev/sr0 找不到介质
    CentOS7 防火墙(firewall)的操作命令
  • 原文地址:https://www.cnblogs.com/yangh2016/p/7773916.html
Copyright © 2011-2022 走看看