Java中配置文件-xx.properties 內容是以鍵值對的形式存儲 不帶分號,比如,在org/zhe/properties這個包下有一個commom.properties文件,內容如下:
name=zhe
age=22
要用到java.util.Properties這個類
Properties
類表示了一個持久的屬性集。Properties
可保存在流中或從流中加載。屬性列表中每個鍵及其對應值都是一個字符串。
代碼如下
package org.zhe.properties;//注意在這個包下
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class LoadProperty {
public static void main(String args[]){
//這裏需要用到Class.getResourceAsStream或者Classloader.Class.getResourceAsStream
//兩者不同之處在於兩者讀取資源的路徑不同
InputStream in = LoadProperty.class.getResourceAsStream("/org/zhe/properties/common.properties");
Properties prop = new Properties();
try {
prop.load(in);
//Properties類的一個方法public void list(PrintStream out)
prop.list(System.out);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(prop.getProperty("name"));
System.out.println(prop.getProperty("age"));
System.out.println(System.getProperty("user.dir")); //Eclipse下就是workspace目錄
System.out.println(LoadProperty.class.getResource(""));
System.out.println(LoadProperty.class.getResource("/"));
System.out.println(LoadProperty.class.getClassLoader().getResource(""));
}
}
輸出結果:
-- listing properties --
age=22
name=zhe
zhe
22
D:\JAVA\MyProject\MyTestProject
file:/D:/JAVA/MyProject/MyTestProject/bin/org/zhe/properties/
file:/D:/JAVA/MyProject/MyTestProject/bin/
file:/D:/JAVA/MyProject/MyTestProject/bin/