properties文件是Java平臺默認的配置文件格式,其優勢是格式清晰,簡單易懂,使用commons-configuration讀取properties文件也比較簡單,代碼以下:html
基本用法:java
1.加載jar包,我使用maven自動加載,pom.xml配置以下:apache
- <dependency>
- <groupId>commons-configuration</groupId>
- <artifactId>commons-configuration</artifactId>
- <version>1.9</version>
- </dependency>
- <dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- <version>2.6</version>
- </dependency>
common-lang這個包要用新版的,若是不寫這個依賴,commons-configuration會下載一個2.1舊版,致使編譯出錯
maven
2.java代碼:spa
- PropertiesConfiguration config = new PropertiesConfiguration(「/database.properties」);
- String userName = config.getString("name");
除了getString()方法外,還有getBoolean,getDouble,getInteger等不一樣返回類型的方法能夠調用。.net
進階用法:orm
一個項目有會有多個配置文件,這時有個統一的配置文件管理類就頗有必要了,我寫了一個簡單的,你們能夠參考下,有不妥的用法也請指出來xml
1.java類htm
- package com.xxx.xxx.util;
-
- import java.util.HashMap;
- import java.util.Map;
-
- import org.apache.commons.configuration.ConfigurationException;
- import org.apache.commons.configuration.PropertiesConfiguration;
- public class configUtil {
-
- private static configUtil initor = new configUtil();
-
- private static Map<String, Object> configMap = new HashMap<String, Object>();
-
- private configUtil() {}
-
-
- public static String get(String configFile, String property) {
- if(!configMap.containsKey(configFile)) {
- initor.initConfig(configFile);
- }
- PropertiesConfiguration config = (PropertiesConfiguration) configMap.get(configFile);
- String value = config.getString(property);
-
- return value;
- }
-
-
- private synchronized void initConfig(String configFile) {
- try {
- PropertiesConfiguration config = new PropertiesConfiguration(configFile);
- configMap.put(configFile, config);
-
- } catch (ConfigurationException e) {
- e.printStackTrace();
- }
- }
- }
2.調用方法blog
- configUtil.get("/common/velocity.properties", "input.encoding");
- public static void readProperties() throws ConfigurationException {
- PropertiesConfiguration pcfg = new PropertiesConfiguration("config/cfg.properties");
- System.out.println(pcfg.getString("platform.jre"));
- }
注意,這裏的路徑必定要搞清楚,配置文件是放在config文件夾中的;