properties配置文件讀取工具類

properties配置文件讀取工具類

    本文中將首先介紹一下讀取properties配置文件的幾種方式,然後詳細介紹基於java.util.ResourceBundle的propertiesUtil工具類寫法。

一、Java讀取properties配置文件的方法,總的來說有3種:

1、基於ClassLoder讀取配置文件

Properties properties = new Properties();
// 使用ClassLoader加載properties配置文件生成對應的輸入流
InputStream in = PropertiesMain.class.getClassLoader().getResourceAsStream("config/config.properties");
// 使用properties對象加載輸入流
properties.load(in);
//獲取key對應的value值
properties.getProperty(String key);

注意:該方式只能讀取類路徑下的配置文件,有侷限但是如果配置文件在類路徑下比較方便。

2、基於 InputStream 讀取配置文件

Properties properties = new Properties();
// 使用InPutStream流讀取properties文件
BufferedReader bufferedReader = new BufferedReader(new FileReader("D:/config.properties"));
properties.load(bufferedReader);
// 獲取key對應的value值
properties.getProperty(String key);

注意:該方式的優點在於可以讀取任意路徑下的配置文件

3、通過 java.util.ResourceBundle 類來讀取

1>通過 ResourceBundle.getBundle() 靜態方法來獲取(ResourceBundle是一個抽象類),這種方式來獲取properties屬性文件不需要加.properties後綴名,只需要文件名即可

properties.getProperty(String key);
//config爲屬性文件名,放在包com.test.config下,如果是放在src下,直接用config即可  
ResourceBundle resource = ResourceBundle.getBundle("com/test/config/config");
String key = resource.getString("keyWord"); 

2>從 InputStream 中讀取,獲取 InputStream 的方法和上面一樣。

ResourceBundle resource = new PropertyResourceBundle(inStream);

注意:這種方式比使用 Properties 要方便一些,獲取properties屬性文件不需要加.properties後綴名,只需要文件名即可。

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

二、基於java.util.ResourceBundle 類來讀取properties配置文件的工具類

java.util.ResourceBundle類如何使用,上面已做了簡單的介紹,在此及直接上代碼了:

package com.wonddream.utils;

import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Parsing The Configuration File
 * 
 */
public final class PropertiesUtil {
	private static Log log = LogFactory.getLog(PropertiesUtil.class);
	
	/**
	 * 根據配置文件路徑和key,獲取配置參數
	 * @param key
	 * @param configPath
	 * @return
	 */
	public static String getString(String key,String configPath) {
        //如果配置文件唯一,可以在類中把configPath成名爲常量,把ResourceBundle對象聲明爲全局靜態變量
		ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(configPath);
		try {
			return RESOURCE_BUNDLE.getString(key);
		} catch (MissingResourceException e) {
			log.error("getString", e);
			return null;
		}
	}

	/**
	 * 根據配置文件路徑和key,獲取配置參數(整型)
	 * @param key
	 * @param configPath
	 * @return
	 */
	public static int getInt(String key,String configPath) {
		return Integer.parseInt(getString(key,configPath));
	}
	
	/*
	 * 測試
	 */
	public static void main(String[] args) {
		System.out.println(getString("redis.address","config/redisConfig"));
	}
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章