一、通過ResourceBundle來讀取.properties文件
/**
* 通過java.util.resourceBundle來解析properties文件。
* @param String path:properties文件的路徑
* @param String key: 獲取對應key的屬性
* @return String:返回對應key的屬性,失敗時候為空。
*/
public static String getPropertyByName1(String path,String key){
String result = null;
try {
result = ResourceBundle.getBundle(path).getString(key).trim();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
對於String path的填寫,要注意。一般分為兩種情況:
1、.properties文件在src目錄下面,文件結構如下所示:
|src/
— —test.properties
2、.properties文件在src目錄下面的一個包中,因為可能我們經常習慣把各種properties文件建立在一個包中。文件結構如下:
|src/
|— —configure/
| | — —test1.properties
| | — —test2.properties
對於第一種情況,在main函數中使用方法如下:
System.out.println(GetConfigureInfo.getPropertyByName1("test", "key1"));
對於第二種情況,在main函數中使用方法如下:
System.out.println(GetConfigureInfo.getPropertyByName1("configure.test1", "key1"));
這種用法下,path不用帶.properties后綴,直接輸入就好了。
二、通過getResourceAsStream方式加載.properties文件
/**
* 解析properties文件。
* @param String path:properties文件的路徑
* @param String key: 獲取對應key的屬性
* @return String:返回對應key的屬性,失敗時候為null。
*/
public String getPropertyByName2(String path,String key){
String result = null;
Properties properties = new Properties();
try {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
if(inputStream == null){
properties.load(inputStream);
result = properties.getProperty(key).trim();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
同樣兩種情況:
1、.properties文件在src目錄下面
使用方法是:
GetConfigureInfo getConfigureInfo = new GetConfigureInfo();
System.out.println(getConfigureInfo.getPropertyByName2("test1.properties", "key1"));
2、.properties文件在src目錄下面的一個包中:
使用方法:
GetConfigureInfo getConfigureInfo = new GetConfigureInfo();
System.out.println(getConfigureInfo.getPropertyByName2("configure/test1.properties", "key1"));
可以看到很明顯的這種類似於文件的讀寫,所以用法有所不同了都。
三、使用FileOutputStream和Propertity寫入test.properties文件:
/**
* 寫入.properties文件, key=content
* @param String path:寫入文件路徑
* @param String key:寫入的key
* @param String content:寫入的key的對應內容
* @return void
*/
public void setProperty(String path,String key,String content){
Properties properties = new Properties();
try {
properties.setProperty(key, content);
//true表示追加。
if((new File(path)).exists()){
FileOutputStream fileOutputStream = new FileOutputStream(path, true);
properties.store(fileOutputStream, "just for a test of write");
System.out.println("Write done");
fileOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
使用方式:
GetConfigureInfo getConfigureInfo = new GetConfigureInfo();
getConfigureInfo.setProperty("src/testConfig.properties", "test3", "test3 value");
值得注意的是,現在這個函數里面的path居然加了src/,因為是用FileOutputStream,所以默認的主路徑是項目路徑。
總結:
對於Java而言,我覺得這些路徑就搞得很不合理的樣子,現在看來,使用輸入輸出流讀寫文件時候,似乎主路徑都是在項目下。
而對於ResourceBundle讀取properties文件的路徑不加.properties也很奇特啊。似乎java中各種不同方式來加載文件時候都有默認的主路徑(也可以說成根目錄)
根目錄也就決定了這個路徑到底應該怎么寫,才能被程序識別。我現在還不得而知,先記錄下這些區別。
如果大家有什么想指正、教育我的地方,歡迎指出,小弟想知道到底是怎么樣子的。
