欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java讀取properties配置文件的8種方式匯總

 更新時間:2022年11月24日 09:29:16   作者:Thinkingcao  
讀取.properties配置文件在實際的開發(fā)中使用的很多,總結(jié)了一下,下面這篇文章主要給大家介紹了關(guān)于Java讀取properties配置文件的8種方式,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下

一、前言

在做Java項目開發(fā)過程中,涉及到一些數(shù)據(jù)庫服務(wù)連接配置、緩存服務(wù)器連接配置等,通常情況下我們會將這些不太變動的配置信息存儲在以 .properties 結(jié)尾的配置文件中。當對應(yīng)的服務(wù)器地址或者賬號密碼信息有所變動時,我們只需要修改一下配置文件中的信息即可。同時為了讓Java程序可以讀取 .properties配置文件中的值,JavaJDK中提供了java.util.Properties類可以實現(xiàn)讀取配置文件。

二、Properties類

Properties 類位于 java.util.Properties中,是Java 語言的處理配置文件所使用的類,其中的xxx.Properties類主要用于集中的持久存儲Java的配置文件內(nèi)容,可以讀取后綴是.properties.cfg的配置文件。

Properties繼承了Hashtable 類,以Map 的形式進行放置值,put(key,value)get(key),文本注釋信息可以用"#"來注釋。

Properties 類表示了一個持久的屬性集。Properties 可保存在流中或從流中加載。屬性列表中每個鍵及其對應(yīng)值都是一個字符串。

Properties 文件內(nèi)容的格式是:鍵=值 形式,Key值不能夠重復(fù)。 例如:

jdbc.driver=com.mysql.jdbc.Driver

Properties類的繼承關(guān)系圖:

Properties類繼承關(guān)系圖

Properties類的源碼關(guān)系圖:

主要方法介紹:

它提供了幾個核心的方法:

  • getProperty ( String key): 用指定的鍵在此屬性列表中搜索屬性。也就是通過參數(shù) key ,得到 key 所對應(yīng)的 value。
  • load ( InputStream inStream): 從輸入流中讀取屬性列表(鍵和元素對)。通過對指定的文件(比如說上面的 test.properties 文件)進行裝載來獲取該文件中的所有鍵 - 值對。以供 getProperty ( String key) 來搜索。
  • setProperty ( String key, String value) : 調(diào)用 Hashtable 的方法 put 。他通過調(diào)用基類的put方法來設(shè)置 鍵 - 值對。
  • store ( OutputStream out, String comments): 以適合使用 load 方法加載到 Properties 表中的格式,將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流。與 load 方法相反,該方法將鍵 - 值對寫入到指定的文件中去。
  • clear (): 清除所有裝載的 鍵 - 值對。該方法在基類中提供。

三、Properties常用方法實踐

Properties類我們從文件的寫入和讀取來實踐其具體用法,下面演示練習將以下數(shù)據(jù)庫配置信息寫入到jdbc.properties文件中

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

項目目錄結(jié)構(gòu)如下

四、Java寫入Properties

Properties類調(diào)用setProperty方法將鍵值對保存到內(nèi)存中,此時可以通過getProperty方法讀取,propertyNames方法進行遍歷,但是并沒有將鍵值對持久化到屬性文件中,故需要調(diào)用store方法持久化鍵值對到屬性文件中。

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

/**
 * @desc:  寫入Mysql數(shù)據(jù)庫了連接信息到j(luò)dbc.properties中
 * @author: cao_wencao
 * @date: 2020-12-29 13:41
 */
public class PropertiesStoreTest {
    public static void main(String[] args) {
        Properties properties = new Properties();
        OutputStream output = null;
        try {
            output = new FileOutputStream("src/main/resources/jdbc.properties");
            properties.setProperty("jdbc.driver", "com.mysql.jdbc.Driver");
            properties.setProperty("jdbc.url","jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8" );
            properties.setProperty("jdbc.username", "root");
            properties.setProperty("jdbc.password", "123456");

            // 保存鍵值對到文件中
            properties.store(output, "Thinkingcao modify");

        } catch (IOException io) {
            io.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

輸出結(jié)果,在resources目錄下多一個文件jdbc.properties,內(nèi)容如下:

#Thinkingcao modify
#Tue Dec 29 13:43:48 CST 2020
jdbc.url=jdbc\:mysql\://localhost\:3306/mybatis?characterEncoding\=utf8
jdbc.username=root
jdbc.driver=com.mysql.jdbc.Driver
jdbc.password=123456

五、Java讀取Properties

Java讀取Properties文件的方法有很多,下面介紹8種方式,分別讀取resource目錄下的jdbc.properties和resource/config/application.properties。

application.properties文件內(nèi)容如下

minio.endpoint=http://localhost:9000
minio.accessKey=minioadmin
minio.secretKey=minioadmin
minio.bucketName=demo

1. 從當前的類加載器的getResourcesAsStream來獲取

/**
     * 1. 方式一
     * 從當前的類加載器的getResourcesAsStream來獲取
     * InputStream inputStream = this.getClass().getResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {
        InputStream inputStream = this.getClass().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("jdbc.url");
        System.out.println("property = " + property);
    }

2. 從當前的類加載器的getClassLoader().getResourcesAsStream來獲取

 /**
     * 2. 方式二
     * 從當前的類加載器的getResourcesAsStream來獲取
     * InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test2() throws IOException {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

3. 使用Class類的getSystemResourceAsStream靜態(tài)方法 和使用當前類的ClassLoader是一樣的

 /**
     * 3. 方式三
     * 使用Class類的getSystemResourceAsStream方法 和使用當前類的ClassLoader是一樣的
     * InputStream inputStream = ClassLoader.getSystemResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test3() throws IOException {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

4. 使用Spring-core包中的ClassPathResource讀取

    /**
     * 4. 方式四
     * Resource resource = new ClassPathResource(path)
     *
     * @throws IOException
     */
    @Test
    public void test4() throws IOException {
        Resource resource = new ClassPathResource("config/application.properties");
        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

5. 從文件中讀取,new BufferedInputStream(InputStream in)

/**
     * 5. 方式五
     * 從文件中獲取,使用InputStream字節(jié),主要是需要加上當前配置文件所在的項目src目錄地址。路徑配置需要精確到絕對地址級別
     * BufferedInputStream繼承自InputStream
     * InputStream inputStream = new BufferedInputStream(new FileInputStream(name)
     * 這種方法讀取需要完整的路徑,優(yōu)點是可以讀取任意路徑下的文件,缺點是不太靈活
     * @throws IOException
     */
    @Test
    public void test5() throws IOException {
        InputStream inputStream = new BufferedInputStream(new FileInputStream("src/main/resources/config/application.properties"));
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

6.從文件中讀取,new FileInputStream(String name)

/**
     * 6. 方式六
     * 從文件中獲取,使用InputStream字節(jié),主要是需要加上當前配置文件所在的項目src目錄地址。路徑配置需要精確到絕對地址級別
     * FileInputStream繼承自InputStream
     * InputStream inputStream = new FileInputStream(name)
     * 這種方法讀取需要完整的路徑,優(yōu)點是可以讀取任意路徑下的文件,缺點是不太靈活
     * @throws IOException
     */
    @Test
    public void test6() throws IOException {
        InputStream inputStream = new FileInputStream("src/main/resources/config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

7. 使用PropertyResourceBundle讀取InputStream流

 /**
     * 7. 方式七
     * 使用InputStream流來進行操作ResourceBundle,獲取流的方式由以上幾種。
     * ResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);
     * @throws IOException
     */
    @Test
    public void test7() throws IOException {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("config/application.properties");
        ResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);
        Enumeration<String> keys = resourceBundle.getKeys();
        while (keys.hasMoreElements()) {
            String s = keys.nextElement();
            System.out.println(s + " = " + resourceBundle.getString(s));
        }
    }

8. 使用ResourceBundle.getBundle讀取

 /**
     * 8. 方式八
     * ResourceBundle.getBundle的路徑訪問和 Class.getClassLoader.getResourceAsStream類似,默認從根目錄下讀取,也可以讀取resources目錄下的文件
     * ResourceBundle rb = ResourceBundle.getBundle("b") //不需要指定文件名的后綴,只需要寫文件名前綴即可
     */
    @Test
    public void test8(){
        //ResourceBundle rb = ResourceBundle.getBundle("jdbc"); //讀取resources目錄下的jdbc.properties
        ResourceBundle rb2 = ResourceBundle.getBundle("config/application");//讀取resources/config目錄下的application.properties
        for(String key : rb2.keySet()){
            String value = rb2.getString(key);
            System.out.println(key + ":" + value);
        }

    }

輸出結(jié)果:

minio.endpoint:http://localhost:9000
minio.bucketName:demo
minio.secretKey:minioadmin
minio.accessKey:minioadmin

六、Properties配合Spring框架使用

加載.properties方式一

<!-- 1.加載 jdbc.properties 配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" system-properties-mode="NEVER"/>

除了上面這種方式之外,還有下面這種List集合的方式

加載.properties方式二

 <!-- 4.引入外部配置文件 由于后期可能會引入多個配置文件 所以采用list的形式 -->
    <bean id="propertyPlaceholder"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:/config/jdbc.properties</value>
                <value>classpath:/config/application.properties</value>
            </list>
        </property>
    </bean>

七、完整代碼

import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @desc: Properties讀取配置文件屬性值的方式
 * @author: cao_wencao
 * @date: 2020-12-29 10:08
 */
public class PropertiesTest {

    /**
     * 1. 方式一
     * 從當前的類加載器的getResourcesAsStream來獲取
     * InputStream inputStream = this.getClass().getResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {
        InputStream inputStream = this.getClass().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("jdbc.url");
        System.out.println("property = " + property);
    }

    /**
     * 2. 方式二
     * 從當前的類加載器的getResourcesAsStream來獲取
     * InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test5() throws IOException {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

    /**
     * 3. 方式三
     * 使用Class類的getSystemResourceAsStream方法 和使用當前類的ClassLoader是一樣的
     * InputStream inputStream = ClassLoader.getSystemResourceAsStream(name)
     *
     * @throws IOException
     */
    @Test
    public void test4() throws IOException {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

    /**
     * 4. 方式四
     * Resource resource = new ClassPathResource(path)
     *
     * @throws IOException
     */
    @Test
    public void test2() throws IOException {
        Resource resource = new ClassPathResource("config/application.properties");
        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

    /**
     * 5. 方式五
     * 從文件中獲取,使用InputStream字節(jié),主要是需要加上當前配置文件所在的項目src目錄地址。路徑配置需要精確到絕對地址級別
     * BufferedInputStream繼承自InputStream
     * InputStream inputStream = new BufferedInputStream(new FileInputStream(name)
     * 這種方法讀取需要完整的路徑,優(yōu)點是可以讀取任意路徑下的文件,缺點是不太靈活
     * @throws IOException
     */
    @Test
    public void test3() throws IOException {
        InputStream inputStream = new BufferedInputStream(new FileInputStream("src/main/resources/config/application.properties"));
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

    /**
     * 6. 方式六
     * 從文件中獲取,使用InputStream字節(jié),主要是需要加上當前配置文件所在的項目src目錄地址。路徑配置需要精確到絕對地址級別
     * FileInputStream繼承自InputStream
     * InputStream inputStream = new FileInputStream(name)
     * 這種方法讀取需要完整的路徑,優(yōu)點是可以讀取任意路徑下的文件,缺點是不太靈活
     * @throws IOException
     */
    @Test
    public void test6() throws IOException {
        InputStream inputStream = new FileInputStream("src/main/resources/config/application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        properties.list(System.out);
        System.out.println("==============================================");
        String property = properties.getProperty("minio.endpoint");
        System.out.println("property = " + property);
    }

    /**
     * 7. 方式七
     * 使用InputStream流來進行操作ResourceBundle,獲取流的方式由以上幾種。
     * ResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);
     * @throws IOException
     */
    @Test
    public void test7() throws IOException {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("config/application.properties");
        ResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);
        Enumeration<String> keys = resourceBundle.getKeys();
        while (keys.hasMoreElements()) {
            String s = keys.nextElement();
            System.out.println(s + " = " + resourceBundle.getString(s));
        }
    }

    /**
     * 8. 方式八
     * ResourceBundle.getBundle的路徑訪問和 Class.getClassLoader.getResourceAsStream類似,默認從根目錄下讀取,也可以讀取resources目錄下的文件
     * ResourceBundle rb = ResourceBundle.getBundle("b") //不需要指定文件名的后綴,只需要寫文件名前綴即可
     */
    @Test
    public void test8(){
        //ResourceBundle rb = ResourceBundle.getBundle("jdbc"); //讀取resources目錄下的jdbc.properties
        ResourceBundle rb2 = ResourceBundle.getBundle("config/application");//讀取resources/config目錄下的application.properties
        for(String key : rb2.keySet()){
            String value = rb2.getString(key);
            System.out.println(key + ":" + value);
        }

    }

    /**
     * 單獨抽取的方法,用戶檢測能否正確操縱Properties
     *
     * @param inputStream
     * @throws IOException
     */
    private void printKeyValue(InputStream inputStream) throws IOException {
        Properties properties = new Properties();
        properties.load(inputStream);
        Set<Object> keys = properties.keySet();
        for (Object key : keys) {
            System.out.println(key + " = " + properties.get(key));
        }
    }
}

總結(jié)

到此這篇關(guān)于Java讀取properties配置文件的8種方式的文章就介紹到這了,更多相關(guān)Java讀取properties配置文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 本地MinIO存儲服務(wù)Java遠程調(diào)用上傳文件的操作過程

    本地MinIO存儲服務(wù)Java遠程調(diào)用上傳文件的操作過程

    MinIO是一款高性能、分布式的對象存儲系統(tǒng),它可以100%的運行在標準硬件上,即X86等低成本機器也能夠很好的運行MinIO,這篇文章主要介紹了本地MinIO存儲服務(wù)Java遠程調(diào)用上傳文件的操作過程,需要的朋友可以參考下
    2023-11-11
  • Gradle構(gòu)建基本的Web項目結(jié)構(gòu)

    Gradle構(gòu)建基本的Web項目結(jié)構(gòu)

    這篇文章主要為大家介紹了Gradle創(chuàng)建Web項目基本的框架結(jié)構(gòu)搭建,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-03-03
  • JavaCV實現(xiàn)人臉檢測功能

    JavaCV實現(xiàn)人臉檢測功能

    這篇文章主要為大家詳細介紹了JavaCV實現(xiàn)人臉檢測功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-02-02
  • java OpenTelemetry日志體系及缺陷解決方案

    java OpenTelemetry日志體系及缺陷解決方案

    這篇文章主要為大家介紹了java OpenTelemetry日志體系及缺陷解決方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-01-01
  • Java中泛型學習之細節(jié)篇

    Java中泛型學習之細節(jié)篇

    泛型在java中有很重要的地位,在面向?qū)ο缶幊碳案鞣N設(shè)計模式中有非常廣泛的應(yīng)用,下面這篇文章主要給大家介紹了關(guān)于Java中泛型細節(jié)的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-02-02
  • springboot整合mqtt的詳細圖文教程

    springboot整合mqtt的詳細圖文教程

    MQTT是一種基于發(fā)布/訂閱(publish/subscribe)模式的“輕量級”通訊協(xié)議,該協(xié)議構(gòu)建于TCP/IP協(xié)議上,由IBM在1999年發(fā)布,下面這篇文章主要給大家介紹了關(guān)于springboot整合mqtt的詳細圖文教程,需要的朋友可以參考下
    2023-02-02
  • Java getResource()如何獲取class文件目錄位置

    Java getResource()如何獲取class文件目錄位置

    這篇文章主要介紹了Java getResource()如何獲取class文件目錄位置,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • Java螺旋矩陣處理方法詳解

    Java螺旋矩陣處理方法詳解

    螺旋矩陣是指一個呈螺旋狀的矩陣,它的數(shù)字由第一行開始到右邊不斷變大,向下變大,向左變大,向上變大,如此循環(huán)。利用java實現(xiàn)的螺旋矩陣,當輸入N之后,會自動打印出螺旋矩陣
    2022-09-09
  • Spring Cloud與分布式系統(tǒng)簡析

    Spring Cloud與分布式系統(tǒng)簡析

    這篇文章主要介紹了Spring Cloud與分布式系統(tǒng)的相關(guān)內(nèi)容,具有一定參考價值,需要的朋友可以了解下。
    2017-09-09
  • LeetCode?動態(tài)規(guī)劃之矩陣區(qū)域和詳情

    LeetCode?動態(tài)規(guī)劃之矩陣區(qū)域和詳情

    這篇文章主要介紹了LeetCode?動態(tài)規(guī)劃之矩陣區(qū)域和詳情,文章基于Java的相關(guān)資料展開對LeetCode?動態(tài)規(guī)劃的詳細介紹,需要的小伙伴可以參考一下
    2022-04-04

最新評論