Properties 文件的編寫與讀取

  1. 編寫 .properties 文件

    1. 文件編寫以 [ key=value ] 格式
    2. = 符號是允許有空格的, 程序讀取時會去除 = 左右空格
    3. 數據以換行來標識結束
  2. 定義類獲取.peroperties文件中的值

    1. 獲取本類 Class 對象
    2. 通過 Class 對象獲取 ClassLoader 類加載器
    3. 通過類加載器的 getResourceAsStream() 方法獲取字節流
    4. 定義 Properties 集合, 調用集合中的 load(inputStream) 來讀取文件
    5. 通過 Properties 集合中的 getProperty("key") 來獲取對於的值

編寫 .properties 文件

key=value
mark=markValue
info=infoVlaue

定義類獲取.peroperties文件中的值

public static void main(String[] args) throws IOException {
    InputStream inputStream = PropertiesDemo.class.getClassLoader().getResourceAsStream("info.properties");
        
    Properties properties = new Properties();
    properties.load(inputStream);
        
    System.out.println("key:[" + properties.getProperty("key") + "]");
    System.out.println("mark:[" + properties.getProperty("mark") + "]");
    System.out.println("info:[" + properties.getProperty("info") + "]");

}

那麼執行程序將輸出結果爲:

key:[value]
mark:[markValue]
info:[infoVlaue]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章