Properties配置文件讀取相關(guān)java知識

** 首發(fā)于www.dongxiaoxia.xyz **

一.getResourceAsStream方法使用

**這里的getResourceAsStream主要是針對ClassClassLoader而言的 **

  1. Class.getResourceAsStream(String path): path 不以’/'開頭時默認是從此類所在的包下取資源,以’/'開頭則是從ClassPath根下獲取。其只是通過path構(gòu)造一個絕對路徑,最終還是由ClassLoader獲取資源。
  2. Class.getClassLoader.getResourceAsStream(String path):默認則是從ClassPath根下獲取,path不能以’/'開頭,最終是由ClassLoader獲取資源。
  3. ServletContext. getResourceAsStream(String path):默認從WebAPP根目錄下取資源,Tomcat下path是否以’/'開頭無所謂,當然這和具體的容器實現(xiàn)有關(guān)。

獲取Class方法
1.XX.class
2.this.getClass()
獲取ClassLoader方法
1.Thread.currentThread().getContextClassLoader()
2.Class.getClassLoader

**getResourceAsStream 用法大致有以下幾種: **

第一: 要加載的文件和.class文件在同一目錄下,例如:com.x.y 下有類me.class ,同時有資源文件myfile.xml
那么,應(yīng)該有如下代碼:
me.class.getResourceAsStream("myfile.xml");
第二:在me.class目錄的子目錄下,例如:com.x.y 下有類me.class ,同時在 com.x.y.file 目錄下有資源文件myfile.xml
那么,應(yīng)該有如下代碼:
me.class.getResourceAsStream("file/myfile.xml");
第三:不在me.class目錄下,也不在子目錄下,例如:com.x.y 下有類me.class ,同時在 com.x.file 目錄下有資源文件myfile.xml
那么,應(yīng)該有如下代碼:
me.class.getResourceAsStream("/com/x/file/myfile.xml");
總結(jié)一下,可能只是兩種寫法
第一:前面有 “ / ”
“ / ”代表了工程的根目錄,例如工程名叫做myproject,“ / ”代表了myproject
me.class.getResourceAsStream("/com/x/file/myfile.xml");
第二:前面沒有 “ / ”
代表當前類的目錄
me.class.getResourceAsStream("myfile.xml");
me.class.getResourceAsStream("file/myfile.xml");
缺點:
getResourceAsStream讀取的文件路徑只局限與工程的源文件夾中,包括在工程src根目錄下,以及類包里面任何位置,但是如果配置文件路徑是在除了源文件夾之外的其他文件夾中時,該方法是用不了的。

二.Properties配置文件的讀取

1.使用Apache Commons Configuration讀取配置信息

第三方標準jar包,容易使用,擁有眾多功能,不用重復(fù)造輪子,但是為了讀取一個配置文件就要引入一個jar包時就要考慮一下了。

2.Spring ResourceLoader

Spring 能支持入?yún)⒙窂降暮芏喾绞剑ㄒ?" /"、"classpath" 開頭。
如果你想在項目中使用 Spring 提供的默認配置文件載入實現(xiàn),可以這樣書寫你的代碼。

ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource("log4j.properties");
Properties props = new Properties();
 props.load(resource.getInputStream());

缺點:依賴于Spring框架,難以通用, 如果用Spring框架應(yīng)該用Spring統(tǒng)一管理配置文件,而不是當作一個工具類使用。

3.通過 java.util.ResourceBundle 對象 操作

通過該方式僅能讀取配置文件而已,不能進行寫操作。示例:

// ResourceBundle rb = ResourceBundle.getBundle("配置文件相對工程根目錄的相對路徑(不含擴展名)");
ResourceBundle rb = ResourceBundle.getBundle("config");
String name = rb.getString("name");

java自帶的類,使用非常簡單,代碼量還少。但是功能略微簡單。

4.通過Properties對象手動寫個工具類

通過Properties對象自定義封裝,更能滿足自己需要的要求。

 /**
     * 根據(jù)Properties配置文件名稱獲取配置文件對象
     *
     * @param propsFileName Properties配置文件名稱(從ClassPath根下獲取)
     * @return Properties對象
     */
    private Properties getProperties(String propsFileName) {
        if (propsFileName == null || propsFileName.equals("")) throw new IllegalArgumentException();
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            try {
                if (propsFileName.lastIndexOf(PROPERTY_FILE_SUFFIX) == -1) {//加入文件名后綴
                    propsFileName += PROPERTY_FILE_SUFFIX;
                }
                //寫法1:
//                inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propsFileName);
                //寫法2:
//                URL url = Thread.currentThread().getContextClassLoader().getResource(propsFileName);
//                inputStream = url.openStream();
                //寫法3:
//                inputStream = PropertiesLoader.class.getClassLoader().getResourceAsStream(propsFileName);
                //寫法4:
//                URL url = PropertyUtil.class.getClassLoader().getResource(propsFileName);
//                inputStream = url.openStream();
                //寫法5:
                inputStream = PropertiesLoader.class.getResourceAsStream("/" + propsFileName);
                if (null != inputStream) properties.load(inputStream);
            } finally {
                if (null != inputStream) {
                    inputStream.close();
                }
            }
        } catch (IOException e) {
//            LOGGER.error("加載屬性文件出錯!", e);
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e);
        }
        return properties;
    }

三.jar包讀取外部和內(nèi)部配置文件

1.獲取文件的方式

把項目打成jar包發(fā)布后jar中的文件就不能通過File file=new File("文件路徑")的方式來讀取文件了。
錯誤方式:

URL url = DBHelper.class.getClassLoader().getResource(configName);
URL url = DBHelper.class.getResource("/db.properties");

從依賴的Jar包中讀取文件, Jar包內(nèi)的文件是無法用File讀取的,只能用Stream的方式讀取。
正確方式:

InputStream inputStraean = DBHelper.class.getClassLoader().getResourceAsStream("db.properties")

結(jié)論:不能傳文件路徑,只能傳輸入流

2.測試獲取文件的各種情況

待測試jar包目錄:


Alt text

測試目錄引用進來的maven目錄


Alt text
Alt text

測試項目目錄
Alt text

待測試jar包運行結(jié)果:


Alt text

測試項目運行結(jié)果
Alt text

根據(jù)測試得到的結(jié)果:

  1. 項目與項目引入jar包的文件都是在classpath下面的,也就是可以通過getResourceAsStream獲取,jar包與項目的獲取方法沒有分別,也就是說,獲取jar內(nèi)部與外部文件的方式是一樣的。
  2. 如果項目與jar包在相對于classpath下有同樣的文件,則以項目的文件覆蓋jar包里面的文件。
  3. jar包里面沒有d.properties,所有jar包里面測試運行沒有找到,但是到了項目里面,在項目下創(chuàng)建d.properties,可是可以發(fā)現(xiàn)該文件的。
  4. 項目可以獲取項目的文件
    項目可以獲取jar包里面的文件
    jar包可以獲取項目的文件
    jar包可以獲取jar包里面的文件
    項目與jar包同時存在該文件,則以項目的文件優(yōu)先

因此,如果開發(fā)一個庫或jar包,可以保留一份默認配置在jar包里面,也可以把配置文件放到客戶端配置,檢測時做處理,如果客戶端配置該文件,則以客戶端的配置為先,沒有找到就用默認配置文件,或者別的處理(拋異常等。。。),slf4j配置我猜也是這樣子吧=_=。

四.Properties配置文件讀取工具類

package xyz.dongxiaoxia.commons.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.logging.Logger;

/**
 * Properties文件載入工具,可載入多個Properties文件,相同屬性在最后載入的文件中的值將會覆蓋之前的值,但以System的Property優(yōu)先。
 *
 * @author dongxiaoxia
 * @create 2016-07-01 23:03
 */
public class PropertiesLoader {

    private static Logger logger = Logger.getLogger(PropertiesLoader.class.getName());

    /**
     * .properties屬性文件名后綴
     */
    public static final String PROPERTY_FILE_SUFFIX = ".properties";

    private final Properties properties;

    public PropertiesLoader(String... propsFileNames) {
        properties = loadProperties(propsFileNames);
    }

    public PropertiesLoader(String propsFileName) {
        properties = getProperties(propsFileName);
    }

    public PropertiesLoader(InputStream inputStream) {
        properties = loadProperties(inputStream);
    }

    public Properties getProperties() {
        return properties;
    }

    /**
     * 取出Property,但與System的Property優(yōu)先,取不到返回空字符串。
     *
     * @param key
     * @return
     */
    private String getValue(String key) {
        String systemProperty = System.getProperty(key);
        if (systemProperty != null) {
            return systemProperty;
        }
        if (properties.containsKey(key)) {
            return properties.getProperty(key);
        }
        return "";
    }

    /**
     * 取出String類型的Property,但與System的Property優(yōu)先,如果都為NUll則拋出異常。
     *
     * @param key
     * @return
     */
    public String getProperty(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return value;
    }

    /**
     * 取出String類型的Property,但以System的Property優(yōu)先,如果都為Null則返回Default值。
     *
     * @param key
     * @param defaultValue
     * @return
     */
    public String getProperty(String key, String defaultValue) {
        String value = getValue(key);
        return value != null ? value : defaultValue;
    }

    /**
     * 取出Integer類型的Property。但以System的Property優(yōu)先,如果都為null或內(nèi)容錯誤則拋異常。
     *
     * @param key
     * @return
     */
    public Integer getInteger(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return Integer.valueOf(value);
    }

    /**
     * 取出Integer類型的Property,但以System的Property優(yōu)先。如果都為null則返回默認值,如果內(nèi)容錯誤則拋異常。
     *
     * @param key
     * @param defaultValue
     * @return
     */
    public Integer getInteger(String key, Integer defaultValue) {
        String value = getValue(key);
        return value != null ? Integer.valueOf(value) : defaultValue;
    }

    /**
     * 取出Double類型的Property,但以System的Property優(yōu)先,如果都為null或內(nèi)容錯誤則拋異常。
     *
     * @param key
     * @return
     */
    public Double getDouble(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return Double.valueOf(value);
    }

    /**
     * 取出Double類型的Property,但以System的Property優(yōu)先,如果都為null則返回默認值,如果內(nèi)容錯誤則拋異常。
     *
     * @param key
     * @param defaultValue
     * @return
     */
    public Double getDouble(String key, Double defaultValue) {
        String value = getValue(key);
        return value != null ? Double.valueOf(value) : defaultValue;
    }

    /**
     * 取出Boolean類型的Property,但以System的Property優(yōu)先,如果都為null則拋出異常,如果內(nèi)容不是true/false則返回false。
     *
     * @param key
     * @return
     */
    public Boolean getBoolean(String key) {
        String value = getValue(key);
        if (value == null) {
            throw new NoSuchElementException();
        }
        return Boolean.valueOf(value);
    }

    /**
     * 取出Boolean類型的Property,但以System的Property優(yōu)先,如果都為null則返回默認值,如果內(nèi)容不為true/false則返回false。
     *
     * @param key
     * @param defaultValue
     * @return
     */
    public Boolean getBoolean(String key, boolean defaultValue) {
        String value = getValue(key);
        return value != null ? Boolean.valueOf(value) : defaultValue;
    }

    public Set<Object> getAllKey() {
        return properties.keySet();
    }

    public Collection<Object> getAllValues() {
        return properties.values();
    }

    public Map<String, Object> getAllKeyValue() {
        Map<String, Object> mapAll = new HashMap<>();
        Set<Object> keys = getAllKey();
        for (Object key1 : keys) {
            String key = key1.toString();
            mapAll.put(key, properties.get(key));
        }
        return mapAll;
    }

    /**
     * 根據(jù)Properties配置文件名稱獲取配置文件對象
     *
     * @param propsFileName Properties配置文件名稱(從ClassPath根下獲取) 可以不帶擴展名
     *                      eg.根目錄下有個common.properties,那么可以傳“common”或者“common.properties”
     *                      根目錄下有個config文件夾,里面存在common.properties,那么可以傳“config/common”或者“config/common.properties”
     * @return Properties對象
     */
    private Properties getProperties(String propsFileName) {
        if (propsFileName == null || propsFileName.equals("")) throw new IllegalArgumentException();
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            try {
                if (propsFileName.lastIndexOf(PROPERTY_FILE_SUFFIX) == -1) {//加入文件名后綴
                    propsFileName += PROPERTY_FILE_SUFFIX;
                }
                //寫法1:
//                inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propsFileName);
                //寫法2:
//                URL url = Thread.currentThread().getContextClassLoader().getResource(propsFileName);
//                inputStream = url.openStream();
                //寫法3:
                inputStream = PropertiesLoader.class.getClassLoader().getResourceAsStream(propsFileName);
                //寫法4:
//                URL url = PropertyUtil.class.getClassLoader().getResource(propsFileName);
//                inputStream = url.openStream();
                //寫法5:
//                inputStream = PropertiesLoader.class.getResourceAsStream("/" + propsFileName);
                if (null != inputStream) properties.load(inputStream);
            } finally {
                if (null != inputStream) {
                    inputStream.close();
                }
            }
        } catch (IOException e) {
//            LOGGER.error("加載屬性文件出錯!", e);
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e);
        }
        return properties;
    }

    /**
     * 載入多個文件
     *
     * @param propsFileNames
     * @return
     */
    private Properties loadProperties(String... propsFileNames) {
        Properties pros = new Properties();
        for (String propsFileName : propsFileNames) {
            InputStream inputStream = null;
            try {
                inputStream = PropertiesLoader.class.getClassLoader().getResourceAsStream(propsFileName);
                pros.load(inputStream);
            } catch (Exception e) {
                logger.info("Could not load properties from path:" + propsFileName + "," + e.getMessage());
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e) {
                    logger.info(e.getMessage());
                }
            }
        }
        return pros;
    }

    /**
     * 根據(jù)輸入流載入Properties對象
     *
     * @param inputStream
     * @return
     */
    private Properties loadProperties(InputStream inputStream) {
        Properties pros = new Properties();
//        pros.load(inputStream);
        try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8")) {
            pros.load(inputStreamReader);
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return pros;
    }
}


更多請查看GItHub PropertiesLoader

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,973評論 6 342
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,779評論 18 399
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,560評論 25 708
  • 第一次讀渡邊淳一的作品是《失樂園》,后來又讀了這位善于描寫性愛作家的《男人這東西》和《女人這東西》,很喜歡這位...
    我是馬依云閱讀 2,565評論 0 0