idea如何讀取配置properties文件以及加載外部文件目錄下的配置

如何去讀properties結尾的文件,方便程序的靈活配置參數
首先建立`PropertiesReader類一般放在util包下面
public class PropertiesReader {

/**
 * 讀取配置文件
 */
private  Properties getProperties(){
    Properties p = null;
    try{
        // 讀取url配置文件configuration.properties爲具體配置文件的名字
      InputStream in = this.getClass().getClassLoader().getResourceAsStream("configuration.properties");
        p = new Properties();
        p.load(in);
    }catch (Exception e){
        System.out.println("====讀取異常====="+e.getMessage());
        p = null;
    }
    return p;
}

/**
 * 查詢配置文件中指定參數對應的值
 */
public static String getProperty(String propertyName){
    PropertiesReader reader = new PropertiesReader();
    Properties p =  reader.getProperties();
    if(null == p)
        return null;
    String result = p.getProperty(propertyName);
    return result;
}

configuration.properties具體如下
在這裏插入圖片描述
項目引入參數

props.put("bootstrap.servers",PropertiesReader.getProperty("product_IP"));
PropertiesReader.getProperty("product_IP")
即可靈活引入參數,方便配置

加載外部文件目錄下的配置
添加filepath

  private  static Logger logger = Logger.getLogger("FilePath");
    //讀取文件路徑 在項目文件的上一次conf文件夾裏面
    public static String getConfFileDir(){
        String path = System.getProperty("user.dir")+File.separator+".."+File.separator + "conf";
        return path;
    }
    public static String getConfFile(String fileNamePath){
        String path = getConfFileDir() + File.separator + fileNamePath;
        judeFileExists(new File(path));
        return path;
    }
    // 判斷文件是否存在
    public static void judeFileExists(File file) {
        if (file.exists()) {
            return;
        } else {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

在ConstantUti修改

 //    配置文件名稱
    public static final String PROPERTIES_PATH = FilePath.getConfFile("外部文件目錄");

PropertiesReader

 private  Properties getProperties(){
        Properties pps = null;
        try{
            // 讀取url配置文件
            InputStream in = new FileInputStream(ConstantUtil.PROPERTIES_PATH);
            pps = new Properties();
            pps.load(in);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("===========讀取配置文件異常========="+e.getMessage());
            pps = null;
        }
        return pps;
    }


/**
     * 查詢配置文件中指定參數對應的值
     * @param propertyName 參數名稱
     */

    public static String getProperty(String propertyName){
        PropertiesReader reader = new PropertiesReader();
        Properties pps =  reader.getProperties();
        if(null == pps)
            return null;
        String result = pps.getProperty(propertyName);
        return result;
    }

其他一切照舊即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章