你會幾種讀取/加載 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);
    }

}

其實這個包還可以自動重載的功能,修改了配置文件不需要重啓服務器即可加載重載配置文件。

 

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

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