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

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

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

一、前言

在做Java項目開發(fā)過程中,涉及到一些數(shù)據(jù)庫服務連接配置、緩存服務器連接配置等,通常情況下我們會將這些不太變動的配置信息存儲在以 .properties 結(jié)尾的配置文件中。當對應的服務器地址或者賬號密碼信息有所變動時,我們只需要修改一下配置文件中的信息即可。同時為了讓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 可保存在流中或從流中加載。屬性列表中每個鍵及其對應值都是一個字符串。

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

jdbc.driver=com.mysql.jdbc.Driver

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

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

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

主要方法介紹:

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

  • getProperty ( String key): 用指定的鍵在此屬性列表中搜索屬性。也就是通過參數(shù) key ,得到 key 所對應的 value。
  • load ( InputStream inStream): 從輸入流中讀取屬性列表(鍵和元素對)。通過對指定的文件(比如說上面的 test.properties 文件)進行裝載來獲取該文件中的所有鍵 - 值對。以供 getProperty ( String key) 來搜索。
  • setProperty ( String key, String value) : 調(diào)用 Hashtable 的方法 put 。他通過調(diào)用基類的put方法來設置 鍵 - 值對。
  • 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ù)庫了連接信息到jdbc.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)文章

  • Java利用反射如何查找使用指定注解的類詳解

    Java利用反射如何查找使用指定注解的類詳解

    這篇文章主要給大家介紹了關(guān)于Java利用反射如何查找使用指定注解的類的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。
    2017-09-09
  • JAVA 日常開發(fā)中Websocket示例詳解

    JAVA 日常開發(fā)中Websocket示例詳解

    JAVA |日常開發(fā)中Websocket詳解,WebSocket是一種在單個TCP連接上進行全雙工通信的協(xié)議,它在Web應用中實現(xiàn)了客戶端與服務器之間的實時數(shù)據(jù)傳輸,本文將詳細介紹Java開發(fā)中WebSocket的使用,包括基本概念、Java API、使用示例以及注意事項,感興趣的朋友一起看看吧
    2024-12-12
  • springcloud client指定注冊到eureka的ip與端口號方式

    springcloud client指定注冊到eureka的ip與端口號方式

    這篇文章主要介紹了springcloud client指定注冊到eureka的ip與端口號方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • SpringBoot使用Mybatis-Generator配置過程詳解

    SpringBoot使用Mybatis-Generator配置過程詳解

    這篇文章主要介紹了SpringBoot使用Mybatis-Generator配置過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-02-02
  • MyBatis-Plus找不到Mapper.xml文件的幾種解決方法

    MyBatis-Plus找不到Mapper.xml文件的幾種解決方法

    mybatis-plus今天遇到一個問題,就是mybatis 沒有讀取到mapper.xml 文件,所以下面這篇文章主要給大家介紹了關(guān)于MyBatis-Plus找不到Mapper.xml文件的幾種解決方法,需要的朋友可以參考下
    2022-06-06
  • java dom4j解析xml文件代碼實例分享

    java dom4j解析xml文件代碼實例分享

    這篇文章主要介紹了java dom4j解析xml文件的方法,分享給大家參考
    2013-12-12
  • mybatis-plus自動填充插入更新時間有8小時時差

    mybatis-plus自動填充插入更新時間有8小時時差

    本文主要介紹了mybatis-plus自動填充插入更新時間有8小時時差,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • 關(guān)于訪問后端接口報404錯誤問題的解決方法(全網(wǎng)最細!)

    關(guān)于訪問后端接口報404錯誤問題的解決方法(全網(wǎng)最細!)

    404頁面的出現(xiàn)會降低用戶體驗,那么導致404頁面出現(xiàn)的原因是什么呢?這篇文章主要給大家介紹了關(guān)于訪問后端接口報404錯誤問題的解決方法,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2023-04-04
  • 解讀java?try?catch?異常后還會繼續(xù)執(zhí)行嗎

    解讀java?try?catch?異常后還會繼續(xù)執(zhí)行嗎

    這篇文章主要介紹了解讀java?try?catch?異常后還會不會繼續(xù)執(zhí)行問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • Java中計算集合中元素的出現(xiàn)次數(shù)統(tǒng)計

    Java中計算集合中元素的出現(xiàn)次數(shù)統(tǒng)計

    本文主要介紹了Java中計算集合中元素的出現(xiàn)次數(shù)統(tǒng)計,使用Collections類配合HashMap來統(tǒng)計和java lamb 計算這兩種方式,具有一定的參考價值,感興趣可以了解一下
    2024-02-02

最新評論