1. 程式人生 > >java讀取.properties配置檔案的幾種方法

java讀取.properties配置檔案的幾種方法

讀取.properties配置檔案在實際的開發中使用的很多,總結了一下,有以下幾種方法(僅僅是我知道的):

一.通過jdk提供的java.util.Properties類

        此類繼承自java.util.HashTable,即實現了Map介面,所以,可使用相應的方法來操作屬性檔案,但不建議使用像put、putAll這 兩個方法,因為put方法不僅允許存入String型別的value,還可以存入Object型別的。因此java.util.Properties類提 供了getProperty()和setProperty()方法來操作屬性檔案,同時使用store或save(已過時)來儲存屬性值(把屬性值寫 入.properties配置檔案)。在使用之前,還需要載入屬性檔案,它提供了兩個方法:load和loadFromXML。

        load有兩個方法的過載:load(InputStream inStream)、load(Reader reader),所以,可根據不同的方式來載入屬性檔案。

        可根據不同的方式來獲取InputStream,如:

1.通過當前類載入器的getResourceAsStream方法獲取下載地址   

  1. InputStream inStream = TestProperties.class.getClassLoader().getResourceAsStream("test.properties");  

2.從檔案獲取

  1. InputStream inStream = 
    new FileInputStream(new File("filePath"));  

3.也是通過類載入器來獲取,和第一種一樣

  1. InputStream in = ClassLoader.getSystemResourceAsStream("filePath");  

4.在servlet中,還可以通過context來獲取InputStream

  1. InputStream in = context.getResourceAsStream("filePath");  

5.通過URL來獲取

  1. URL url = new URL("path");  
  2. InputStream inStream = url.openStream();  

讀取方法如下:

  1. Properties prop = new Properties();    
  2. prop.load(inStream);    
  3. String key = prop.getProperty("username");    
  4. //String key = (String) prop.get("username");

二.通過java.util.ResourceBundle類讀取

        這種方式比使用Properties要方便一些。

1.通過ResourceBundle.getBundle()靜態方法來獲取

        ResourceBundle是一個抽象類,這種方式來獲取properties屬性檔案不需要加.properties字尾名,只需要檔名即可。

  1. ResourceBundle resource = ResourceBundle.getBundle("com/mmq/test");//test為屬性檔名,放在包com.mmq下,如果是放在src下,直接用test即可  
  2. String key = resource.getString("username");  

2.從InputStream中讀取

        獲取InputStream的方法和上面一樣,不再贅述。

  1. ResourceBundle resource = new PropertyResourceBundle(inStream);  

        注意:在使用中遇到的最大的問題可能是配置檔案的路徑問題,如果配置檔案入在當前類所在的包下,那麼需要使用包名限定, 如:test.properties入在com.mmq包下,則要使用com/mmq/test.properties(通過Properties來獲 取)或com/mmq/test(通過ResourceBundle來獲取);屬性檔案在src根目錄下,則直接使用test.properties 下載地址   或test即可。

三.例項

ResourceLoader.java

  1. package com.bijian.study;  
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6. import java.util.Properties;  
  7. publicfinalclass ResourceLoader {  
  8.     privatestatic ResourceLoader loader = new ResourceLoader();  
  9.     privatestatic Map<String, Properties> loaderMap = new HashMap<String, Properties>();  
  10.     private ResourceLoader() {  
  11.     }  
  12.     publicstatic ResourceLoader getInstance() {  
  13.         return loader;  
  14.     }  
  15.     public Properties getPropFromProperties(String fileName) throws Exception {  
  16.         Properties prop = loaderMap.get(fileName);  
  17.         if (prop != null) {  
  18.             return prop;  
  19.         }  
  20.         String filePath = null;  
  21.         String configPath = System.getProperty("configurePath");  
  22.         if (configPath == null) {  
  23.             filePath = this.getClass().getClassLoader().getResource(fileName).getPath();  
  24.         } else {  
  25.             filePath = configPath + "/" + fileName;  
  26.         }  
  27.         prop = new Properties();  
  28.         prop.load(new FileInputStream(new File(filePath)));  
  29.         loaderMap.put(fileName, prop);  
  30.         return prop;  
  31.     }  
  32. }  

PropertiesUtil.java

  1. package com.bijian.study;  
  2. import java.util.Properties;  
  3. import java.util.concurrent.ConcurrentHashMap;  
  4. import java.util.concurrent.ConcurrentMap;  
  5. /** 
  6.  * 用ConcurrentMap來快取屬性檔案的key-value 
  7.  */
  8. publicclass PropertiesUtil {  
  9.     privatestatic ResourceLoader loader = ResourceLoader.getInstance();  
  10.     privatestatic ConcurrentMap<String, String> configMap = new ConcurrentHashMap<String, String>();  
  11.     privatestaticfinal String DEFAULT_CONFIG_FILE = "test.properties";  
  12.     privatestatic Properties prop = null;  
  13.     publicstatic String getStringByKey(String key, String propName) {  
  14.         try {  
  15.             prop = loader.getPropFromProperties(propName);  
  16.         } catch (Exception e) {  
  17.             thrownew RuntimeException(e);  
  18.         }  
  19.         key = key.trim();  
  20.         if (!configMap.containsKey(key)) {  
  21.             if (prop.getProperty(key) != null) {  
  22.                 configMap.put(key, prop.getProperty(key));  
  23.             }  
  24.         }  
  25.         return configMap.get(key);  
  26.     }  
  27.     publicstatic String getStringByKey(String key) {  
  28.         return getStringByKey(key, DEFAULT_CONFIG_FILE);  
  29.     }  
  30.     publicstatic Properties getProperties() {  
  31.         try {  
  32.             return loader.getPropFromProperties(DEFAULT_CONFIG_FILE);  
  33.         } catch (Exception e) {  
  34.             e.printStackTrace();  
  35.             returnnull;  
  36.         }  
  37.     }  
  38. }  

Constant.java

  1. package com.bijian.study;  
  2. publicclass Constant {  
  3.     publicstaticfinal String TEST = PropertiesUtil.getStringByKey("test""test.properties");  
  4. }  

Main.java

  1. package com.bijian.study;  
  2. publicclass Main {  
  3.     publicstaticvoid main(String[] args) {  
  4.         System.out.println(Constant.TEST);  
  5.     }  
  6. }