Java中的Properties類
前言
Java中的Properties類屬於配置文件,以鍵值對的方式存儲,可以看做是屬性集。
Properties類(Java.util.Properties)繼承Hashtable(Java.util.Hashtable)
主要方法
- getProperty ( String key):用指定的鍵在此屬性列表中搜索屬性。也就是通過參數 key ,得到 key 所對應的 value。
- load ( InputStream inStream):從輸入流中讀取屬性列表(鍵和值)。通過對指定的文件(比如test.properties 文件)進行裝載來獲取該文件中的所有鍵值對。以供 getProperty ( String key) 來搜索。
- setProperty ( String key, String value):他通過調用父類的put方法來設置鍵值對。
- store ( OutputStream out, String comments):將此 Properties 表中的屬性列表(鍵和值)寫入輸出流。與 load 方法相反,該方法將鍵值對寫入到指定的文件中去。
- clear ():清除所有裝載的鍵值對。該方法由父類中提供。
- Enumeration<?> propertyNames():返回Properties中的key值。
讀取Properties文件
- 基於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);
- 基於 InputStream 讀取配置文件
Properties properties = new Properties();
// 使用InPutStream流讀取properties文件
BufferedReader bufferedReader = new BufferedReader(new FileReader("E:/config.properties"));
properties.load(bufferedReader);
// 獲取key對應的value值
properties.getProperty(String key);
- 通過 java.util.ResourceBundle 類來讀取
- 通過 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");
- 從InputStream中讀取,獲取InputStream的方法和上面一樣.
相關實例
- 獲取JVM的系統屬性
- Java虛擬機(JVM)有自己的系統配置文件(system.properties),我們可以通過下面的方式來獲取
import java.util.Properties;
public class ReadJVM {
public static void main(String[] args) {
Properties pps = System.getProperties();
pps.list(System.out);
}
}
- 讀取一個Perperties文件中的全部信息
public static void main(String[] args) throws Exception, IOException {
Properties prop = new Properties();
prop.load(new FileReader("config/proper.porperties"));
Enumeration<?> propertyNames = prop.propertyNames();
while(propertyNames.hasMoreElements()){
String key = (String) propertyNames.nextElement();
System.out.println(key + "=" + prop.getProperty(key));
}
相關參考:
Java中Properties類的操作
讀取Properties文件的3中方式
以上
@Fzxey