Java Properties集合基礎決議
本期學習的properties集合是專案中經常用到的操作
什么是Properties集合?
java.util.Properties集合繼承于Hashtable,來表示一個持久的屬性集,他使用鍵值結構存盤資料,每個鍵及其對應的值都是一個字串,該類被許多java類使用,比如獲取系統屬性時,System.getProperties,方法就是回傳一個Properties物件
properties集合是唯一一個與IO流相結合的集合
可以使用Properties集合中的方法store把集合中的資料持久化
可以使用Properties集合中的load方法,把硬碟中保存的檔案(鍵值對)存盤到集合中使用,這在專案中 用于讀取組態檔經常使用到
屬性表中每個鍵及其對應值都是一個字串
Properties集合是一個雙列集合(雙列集合是每個元素由鍵和值兩部分組成,由鍵可以找到值,鍵必須是唯一的,值可以重復)
構造方法
public properties() 創建一個空的屬性串列
基本的存盤方法:
public Object setProperty(String key,String value) :保存一對屬性
public String setProperties(String key) :使用此屬性串列中指定的鍵搜索屬性值
public Set
public class Main {
public static void main(String[] args) {
Properties properties = new Properties();
//存入鍵值對
properties.setProperty("one","1");
properties.setProperty("two","2");
//拿出所有鍵
Set<String> strings = properties.stringPropertyNames();
//遍歷鍵
for (String string : strings) {
//通過鍵獲取值
String property = properties.getProperty(string);
//輸出
System.out.println(string+":"+property);
}
}
}
結果

與流相關的方法
store ( OutputStream out, String comments)
store ( OutputStream out, String comments) : 以適合使用 load 方法加載到 Properties 表中的格式,將此 Properties 表中的屬性串列(鍵和元素對)寫入輸出流,與 load 方法相反,該方法將鍵 - 值對寫入到指定的檔案中去,
引數中使用了位元組輸入流,通過流物件,可以關聯到某檔案上,這樣就可以能夠加載文本中的資料了,文本資料格式:
public class Main {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
//存入鍵值對
properties.setProperty("one","1");
properties.setProperty("two","2");
//加載文本中資訊到屬性集
properties.store(new FileWriter("c.text"),"savedate");
//拿出所有鍵
Set<String> strings = properties.stringPropertyNames();
}
}
結果

public void load(InputStream inStream)
public void load(InputStream inStream) : 從位元組輸入流中讀取鍵值對,
注意:
1.存盤鍵值對的檔案中,鍵與值默認的鏈接符號可以使用=,空格等其他符號
2.存盤鍵值對的檔案中,可以使用“#”進行注釋,被注釋的鍵值對默認不會被讀取
3.存盤鍵值對的檔案中,鍵與值都是字串,不要加引號
public class Main {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.load(new FileReader("c.text"));
//拿出所有鍵
Set<String> strings = properties.stringPropertyNames();
for (String string : strings) {
System.out.println(string+":"+properties.getProperty(string));
}
}
}
結果

以上就是Properties集合的一些基礎知識,如有錯誤請各位批評指正,喜歡我的文章可以點贊收藏,我會不定期更新文章,各位道友也可以關注我

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/140456.html
標籤:Java
上一篇:Redis中的Scan命令踩坑記
下一篇:如何使用java命令生成檔案
