Properties是唯一可以和IO流對接的集合可以使用Properties集合存儲數據,遍歷取出Properties集合中的數據
Properties 類表示了一個持久的屬性集。Properties 可保存在流中或從流中加載。屬性列表中每個鍵及其對應值都是一個字符串。
可以使用Properties集合中的方法store,把集合中的臨時數據,持久化寫入到硬盤中存儲
可以使用Properties集合中的方法load,把硬盤中保存的文件(鍵值對),讀取到集合中使用
package Properties;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
public class properties {
public static void main(String[] args) throws IOException {
//show01();
//show02();
show03();
}
/*
* 可以使用Properties集合中的方法load,把硬盤中保存的文件(鍵值對),讀取到集合中使用
void load(InputStream inStream)
* void load(Reader reader)
* 使用步驟
* 1.創建Properties集合對象
* 2.使用Properties集合對象中的方法load讀取保存鍵值對的文件
* 3.遍歷Properties集合
* 注意:存儲鍵值對的文件中,鍵與值的默認連接符爲=,空格(其他符號)
* 可以使用#進行註釋,被註釋的鍵值對不會再被讀取
* 鍵與值默認都是字符串,不用再加引號
* */
private static void show03() throws IOException {
Properties prop = new Properties();
prop.load(new FileReader("C:\\IdeaProjects\\untitled1\\a.properties.txt"));
Set<String > set = prop.stringPropertyNames();
for(String key:set){
String value = prop.getProperty(key);
System.out.println(key+"="+value);
}
}
/*
* void store(OutputStream out, String comments)
void store(Writer writer, String comments)
參數:OutputStream字節輸出流
* Writer字符輸出流
* String comments:註釋(不能出現漢字)
* 一般設置爲一個空的字符串
* 使用步驟:1.創建Properties集合對象,添加數據
* 2.創建字節輸出流/字符輸出流對象,構造方法中綁定要輸出的目的地
* 3.使用Properties集合中的方法store,把集合中的臨時數據,持久化寫入到硬盤中存儲
* 4.釋放資源
* */
private static void show02() throws IOException {
Properties prop = new Properties();
//往集合中添加數據
prop.setProperty("趙麗穎","168");
prop.setProperty("楊穎","165");
prop.setProperty("李冰冰","175");
//2.創建字節輸出流/字符輸出流對象,構造方法中綁定要輸出的目的地
FileWriter fw = new FileWriter("C:\\IdeaProjects\\untitled1\\a.properties.txt");
// 3.使用Properties集合中的方法store,把集合中的臨時數據,持久化寫入到硬盤中存儲
prop.store(fw," ");
//4.釋放資源
fw.close();
}
/*public Object setProperty(String key,String value)調用 Hashtable 的方法 put。
String getProperty(String key, String defaultValue)*/
private static void show01(){
Properties prop = new Properties();
//往集合中添加數據
prop.setProperty("趙麗穎","168");
prop.setProperty("楊穎","165");
prop.setProperty("李冰冰","175");
//使用stringPropertyNames把properties集合中的鍵取出,存儲一個Set集合
Set<String> set = prop.stringPropertyNames();
//遍歷Set集合,取出Properties集合的每一個鍵
for(String key:set){
//使用getProperty方法通過key獲取value
String value = prop.getProperty(key);
System.out.println(key+"="+value);
}
}
}