天天看點

java加載配置檔案,并讀取配置參數

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.util.Properties;

public class Configuration {

    private static Properties properties = new Properties();

    static{
        try{
            /*方法一:通過配置檔案的絕對路徑           
            String confPath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "config.properties";
            BufferedReader bufferedReader = new BufferedReader(new FileReader(confPath));
            properties.load(bufferedReader);
            */
            /*方法二:通過搜尋類路徑,比如/xxx/xxx/config/config.properties,則啟動程式時通過-cp指定類路徑,即java -cp /xxx/xxx/config 
            */
            ClassLoader classLoader = Configuration.class.getClassLoader();
            URL url = classLoader.getResource("config.properties");
            BufferedReader bufferedReader = new BufferedReader(new FileReader(url.getPath()));
            properties.load(bufferedReader);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static String getProperty(String key){
        return properties.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue){
        return properties.getProperty(key,defaultValue);
    }
}