Java 自定义方法 - CNF

来自牛奶河Wiki
阿奔讨论 | 贡献2024年3月3日 (日) 23:18的版本
跳到导航 跳到搜索

Java 自定义函数 - CNF

从配置文件中获取 item 定义 name1, name2,...,配置文件格式:

item.name1=value
item.name2=value
No Method Explain Example
0 CNF 读配置文件,支持全路径,默认当前目录下 config 目录 CNF cnf1 = new CNF("sys.cnf")
get 获取指定 key 值或全部值
put 将指定 item 组值放入 MAP cnf1.put(dbinfo, "db_" + sType)
package com.udf.base;
/*
------------------------------------------------------------------------------
  Name     : Udf.base.CNF
  Purpose  : get config
  Author   : Adam
  Revisions:
  Ver        Date        Author           Description
  ---------  ----------  ---------------  ------------------------------------
  1.0        2024/2/7    Adam

 format:
    property:
    method  : get, put
------------------------------------------------------------------------------
*/
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

public class CNF extends BASE {
    public static final String VERSION = "v1.0";
    private static final Properties dCnf = new Properties();
    private static final Logger logger = Logger.getLogger(CNF.class);

    public CNF(String sFile) {
        // get config, if not path, default ./config/
        String sPath;
        if (sFile.indexOf('/') >= 0)
            sPath = sFile;
        else
            sPath = System.getProperty("user.dir") + "/config/" + sFile;

        // config file contents --> dCnf(Properties)
        try {
            File fFile = new File(sPath);
            if (!fFile.isFile()) {
                //throw new RuntimeException("File Read Error." + sFile);
                logger.error(String.format("File %s Read Error.", sFile));
            }else {
                InputStream is = new FileInputStream(fFile);
                dCnf.load(is);
                is.close();
            }
        } catch (Exception e) {
            logger.error(String.valueOf(e));
        }
        //System.out.println(dCnf);
    }

    public Properties get() {
        return dCnf;
    }
    public String get(String key) {
        return dCnf.getProperty(key);
    }
    // put {sKey}{sKeyp}* Properties --> map
    public void put(HashMap<String, String> mKV, String sKey, String sKeyp) {
        String str1;
        for (String key : dCnf.stringPropertyNames()) {
            if (key.indexOf(sKey) == 0) {
                str1 = ltrim(key, sKey);
                str1 = ltrim(str1, sKeyp);
                mKV.put(str1, dCnf.getProperty(key));
            }
        }
    }
    // default: item --> item.
    public void put(HashMap<String, String> mKV, String sKey) {
        put(mKV, sKey, ".");
    }
}