在實際開發中, 爲了項目配置的靈活, 參數設置一般都會放到配置文件中, 比如:
log4j.properties jdbc.properties 等等
這些配置文件一般情況下, 使用框架, 交給spring加載, 但是如果讓我們自己讀取配置信息, 該怎麼辦?
有一些時候, 我們需要自己根據業務需求, 來讀取不同的配置文件信息,
下面案例, 兩個方法都可以, 一個靜態, 一個動態, 根據需要使用:
package utils;
import java.io.IOException;
import java.util.Properties;
import java.util.ResourceBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author wxy e-mail:[email protected]
* @date 創建時間:2017年5月18日 上午9:28:00
* @version 1.0
* @company: xxx科技公司
* @description: 讀取配置文件
* */
public class ReadConfigUtils {
private static Logger logger= LoggerFactory.getLogger(ReadConfigUtils.class);
/**
* @param resourceName 要讀取的資源文件名稱: 如:jdbc.properties ps:文件的後綴名properties不能傳進去,否則報錯
* @param property 要讀取的資源文件中的某一個屬性名: 如url, username, password.....
* @return 返回屬性值
*/
public static String getDataFromPropertiseFile(String resourceName, String property) {
if (resourceName == null || "".equals(resourceName)) {
logger.debug("getDataFromPropertiseFile resourceName is null, 讀取的資源文件不存在");
return null;
}
if (property == null || "".equals(property)) {
logger.debug("getDataFromPropertiseFile property is null 資源文件中, 沒有這個屬性值");
return null;
}
ResourceBundle resource = null;
try {
resource = ResourceBundle.getBundle(resourceName);
if (resource == null) {
logger.debug(resourceName + "配置文件不存在");
return null;
}
return resource.getString(property);
} catch (Exception e) {
logger.error(resourceName + "配置文件不存在", e);
return null;
}
}
/**
* 這是一個讀取.properties配置文件的類, 如jdbc.properties.
* @param str 讀取的配置文件路徑, 默認路徑是classpath下
*
* @return 返回讀取好的配置文件信息 這個返回值可以用.getProperty("屬性名") 拿到相對應的屬性值.
*/
public Properties readConfig(String str) {
Properties prop = new Properties();
try {
prop.load(this.getClass().getClassLoader().getResourceAsStream(str));
} catch (NullPointerException e2) {
e2.printStackTrace();
System.out.println("空指針異常, 找不到這個配置文件");
return null;
} catch (IOException e3) {
e3.printStackTrace();
System.out.println("流讀取異常");
return null;
}catch (Exception e) {
e.printStackTrace();
System.out.println("讀取配置文件信息: " + str + " 失敗");
return null;
}
return prop;
}
/**
* 驗證方法
*
* @throws Exception
*/
public static void main(String[] args) {
ReadConfigUtils r = new ReadConfigUtils();
Properties config = r.readConfig("wxy/demo/jdbc2.properties");
// Properties config = r.readConfig("jdbc.properties");
System.out.println("123");
System.out.println(config.getProperty("name"));
System.out.println(config.getProperty("password"));
System.out.println(config.getProperty("wxy"));
System.out.println("....................分割線............................");
String value = ReadConfigUtils.getDataFromPropertiseFile("wxy/demo/jdbc2", "name");
System.out.println(value);
}
}