生活随笔
收集整理的這篇文章主要介紹了
读取不同位置的配置文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在開發和測試環境中,很容易混淆如何獲取不同位置的配置文件。為了避免重復造輪子,在此記錄一下自己的解決方案:
可以提出如下設想:
1、在開發環境下,讀取resources下的config.properties文件
2、在生產環境下,讀取jar文件同級目錄下的config.properties文件,如果沒有該config.properties文件,則讀取jar包中的config.properties
1 public class ConfigUtils {
2 /**
3 * 根據配置文件中的內容獲取配置信息內容
4 * @param property 配置的屬性
5 * @return 配置屬性值
6 * @throws IOException
7 */
8 public static String getProperty(String property)
throws IOException {
9 Properties properties =
new Properties();
10 InputStream inputStream =
null;
11 // 獲取.jar文件同級目錄下,config.properties文件的絕對路徑
12 String configFilePath = System.getProperty("user.dir") + File.separator + "config.properties"
;
13 // 如果在.jar文件同級目錄下,config.properties文件存在,則使用該文件作為配置文件
14 if (
new File(configFilePath).exists()) {
15 inputStream =
new BufferedInputStream(
new FileInputStream(configFilePath));
16 }
else {
17 //如果在.jar文件同級目錄下,config.properties文件不存在,則使用.jar文件中的config.properties文件作為配置文件
18 inputStream = ConfigUtils.
class.getClassLoader().getResourceAsStream("config.properties"
);
19 }
20 properties.load(inputStream);
21 String value =
properties.getProperty(property);
22 return value;
23 }
24 }
?
轉載于:https://www.cnblogs.com/ppcoder/p/9006036.html
總結
以上是生活随笔為你收集整理的读取不同位置的配置文件的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。