1. 程式人生 > 其它 >你會幾種讀取/載入 properties配置檔案方法

你會幾種讀取/載入 properties配置檔案方法

摘要:在java專案中經常會使用到配置檔案,這裡就介紹幾種載入配置檔案的方法。

本文分享自華為雲社群《【Java】讀取/載入 properties配置檔案的幾種方法》,作者:Copy工程師。

說明

在java專案中經常會使用到配置檔案,這裡就介紹幾種載入配置檔案的方法

目錄結構

我是使用的maven搭建的專案,resources其實就是在根目錄下
配置檔案很簡單

一、 基於ClassLoader讀取配置檔案

注意:有侷限性只能在類路徑下比較方便

Properties properties = new Properties();
// 注意這裡的路徑是根據根目錄寫的
InputStream in
= ReadProperties.class.getClassLoader().getResourceAsStream("conf/demo.properties"); properties.load(in); System.out.println("1111111111111---->:"+properties.getProperty("name")); 輸出: 1111111111111---->:xing

二、基於InputStream讀取配置檔案

Properties properties2 = new Properties();
// 以下兩種獲取檔案流的方式都可以,對於小檔案第一種更快一點

// 通過BufferedReader獲取檔案流 try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) { properties2.load(bufferedReader); System.out.println("22222222222---->:"+properties2.getProperty("name")); }catch (Exception e){ e.printStackTrace(); } // 通過FileInputStreamm獲取檔案流 InputStream in2 = new
FileInputStream(new File(filePath)); properties2.load(in2); System.out.println("22222222222---->:"+properties2.getProperty("name")); 輸出: 22222222222---->:xing 22222222222---->:xing

三、基於ResourceBundle讀取配置檔案

// 1. 通過ResourceBundle.getBundle() 靜態方法來獲取檔案 這種方式不需要新增字尾名
 // 注意這裡的ResourceBundle.getBundle("conf/demo") 這裡不需要寫配置檔案的字尾 只需要名字即可 xml沒試過 這裡是properties
ResourceBundle resourceBundle = ResourceBundle.getBundle("conf/demo");
System.out.println("333333333333----->:"+resourceBundle.getString("name"));
// 2. 通過InputStream讀取檔案
InputStream in3 = new FileInputStream(new File(filePath));
ResourceBundle resourceBundle2 = new PropertyResourceBundle(in3);
System.out.println("333333333333----->:"+resourceBundle2.getString("name"));

輸出:
333333333333----->:xing
333333333333----->:xing

四、基於PropertiesConfiguration讀取配置檔案 需要使用第三方的包

這是我推薦使用的方法,畢竟有大腿在,幹嘛不去抱大腿,嘿嘿。我使用的包是commons-configuration2.x 。記住這是版本2 ,不是版本1, 2和1有很大的差別的。

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-configuration2 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-configuration2</artifactId>
    <version>2.2</version>
</dependency>

try {
    // 直接通過路徑讀取檔案
    Configurations configurations = new Configurations();
    FileBasedConfigurationBuilder.setDefaultEncoding(PropertiesConfiguration.class, "UTF-8");
    PropertiesConfiguration propertiesConfiguration = configurations.properties(filePath);
    System.out.println("444444444444----->:"+propertiesConfiguration.getString("name"));
    //通過reader 讀取檔案 找了找好像沒有通過InputStream讀取檔案的方式
    PropertiesConfiguration propertiesConfiguration1 = new PropertiesConfiguration();
    propertiesConfiguration1.read(new BufferedReader(new FileReader(new File(filePath))));
    System.out.println("555555555555----->:"+propertiesConfiguration1.getString("name"));
} catch (org.apache.commons.configuration2.ex.ConfigurationException e) {
    e.printStackTrace();
}

輸出:
444444444444----->:xing
555555555555----->:xing

整個類:

package com.xing.test;

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import java.io.*;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

public class ReadProperties {
    public static void main(String[] args) throws IOException {
        String filePath = ReadProperties.class.getClassLoader().getResource("conf/demo.properties").getPath();

        /** 方法一
         *  基於ClassLoader讀取配置檔案
         *  有侷限性 只能在類路徑下比較方便
         */
        Properties properties = new Properties();
        // 注意這裡的路徑是根據target/classes 的路徑寫的
        InputStream in = ReadProperties.class.getClassLoader().getResourceAsStream("conf/demo.properties");
        properties.load(in);
        System.out.println("1111111111111---->:"+properties.getProperty("name"));
        /** 方法二
         *  基於InputStream讀取配置檔案
         *
         */
        Properties properties2 = new Properties();
        // 兩種獲取檔案流的方式都可以,對於小檔案第一種更快一點
        // 通過BufferedReader獲取檔案流
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
            properties2.load(bufferedReader);
            System.out.println("22222222222---->:"+properties2.getProperty("name"));
        }catch (Exception e){
            e.printStackTrace();
        }
        // 通過FileInputStreamm獲取檔案流
        InputStream in2 = new FileInputStream(new File(filePath));
        properties2.load(in2);
        System.out.println("22222222222---->:"+properties2.getProperty("name"));
        /** 方法三
         *  基於ResourceBundle讀取配置檔案
         *
         */
        // 1. 通過ResourceBundle.getBundle() 靜態方法來獲取檔案 這種方式不需要新增字尾名
        ResourceBundle resourceBundle = ResourceBundle.getBundle("conf/demo");
        System.out.println("333333333333----->:"+resourceBundle.getString("name"));
        // 2. 通過InputStream讀取檔案
        InputStream in3 = new FileInputStream(new File(filePath));
        ResourceBundle resourceBundle2 = new PropertyResourceBundle(in3);
        System.out.println("333333333333----->:"+resourceBundle2.getString("name"));
        /** 方法四
         *  基於PropertiesConfiguration讀取配置檔案 需要使用第三方的包
         *
         */

        try {
            Configurations configurations = new Configurations();
            FileBasedConfigurationBuilder.setDefaultEncoding(PropertiesConfiguration.class, "UTF-8");
            PropertiesConfiguration propertiesConfiguration = configurations.properties(filePath);
            System.out.println("444444444444----->:"+propertiesConfiguration.getString("name"));
            //InputStream in4 = new FileInputStream(new File(filePath));
            PropertiesConfiguration propertiesConfiguration1 = new PropertiesConfiguration();
            propertiesConfiguration1.read(new BufferedReader(new FileReader(new File(filePath))));
            System.out.println("555555555555----->:"+propertiesConfiguration1.getString("name"));
        } catch (org.apache.commons.configuration2.ex.ConfigurationException e) {
            e.printStackTrace();
        }
    }
}

後記

通常在讀取配置檔案的時候都是寫個工具類,在程式執行的時候就載入配置檔案了。這裡簡單寫了一個,湊合著看吧。

package com.xing.test;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PropertiesUtils {

    private static final Log log = LogFactory.getLog(PropertiesUtils.class);

    private static Configurations configurations = null;
    private static PropertiesConfiguration propertiesConfiguration = null;
    private static void initProperties(){
        configurations = new Configurations();
        FileBasedConfigurationBuilder.setDefaultEncoding(PropertiesConfiguration.class, "UTF-8");
        try {
            propertiesConfiguration = configurations.properties(PropertiesUtils.class.getClassLoader().getResource("conf/demo.properties"));
        } catch (ConfigurationException e) {
            log.error("配置檔案初始化失敗",e);
        }
    }
    static {
        initProperties();
    }

    /**
     *  獲取String型別的value
     * @param key
     * @return
     */
    public static String getValueString(String key){
        if (propertiesConfiguration == null){
            initProperties();
        }
        return propertiesConfiguration.getString(key);
    }

    /**
     * 獲取int型別的value
     * @param key
     * @return
     */
    public static int getValueInt(String key){
        if (propertiesConfiguration == null){
            initProperties();
        }
        return propertiesConfiguration.getInt(key, 0);
    }

}

其實這個包還可以自動過載的功能,修改了配置檔案不需要重啟伺服器即可載入過載配置檔案。

點選關注,第一時間瞭解華為雲新鮮技術~