標籤:comment text class load prope reader data input 一個
Properties類介紹
Properties 類表示了一個持久的屬性集。Properties 可儲存在流中或從流中載入。屬性列表中每個鍵及其對應值都是一個字串。
特點:
1、Hashtable的子類,map集合中的方法都可以用。
2、該集合沒有泛型。索引值都是字串。
3、它是一個可以持久化的屬性集。索引值可以儲存到集合中,也可以儲存到持久化的裝置(硬碟、隨身碟、光碟片)上。索引值的來源也可以是持久化的裝置。
4、有和流技術相結合的方法。
l load(InputStream) 把指定流所對應的檔案中的資料,讀取出來,儲存到Propertie集合中
l load(Reader)
l store(OutputStream,commonts)把集合中的資料,儲存到指定的流所對應的檔案中,參數commonts代表對描述資訊
l stroe(Writer,comments);
代碼示範:
/*
*
* Properties集合,它是唯一一個能與IO流互動的集合
*
* 需求:向Properties集合中添加元素,並遍曆
*
* 方法:
* public Object setProperty(String key, String value)調用 Hashtable 的方法 put。
* public Set<String> stringPropertyNames()返回此屬性列表中的鍵集,
* public String getProperty(String key)用指定的鍵在此屬性列表中搜尋屬性
*/
public class PropertiesDemo01 {
public static void main(String[] args) {
//建立集合對象
Properties prop = new Properties();
//添加元素到集合
//prop.put(key, value);
prop.setProperty("周迅", "張學友");
prop.setProperty("李小璐", "賈乃亮");
prop.setProperty("楊冪", "劉愷威");
//System.out.println(prop);//測試的使用
//遍曆集合
Set<String> keys = prop.stringPropertyNames();
for (String key : keys) {
//通過鍵 找值
//prop.get(key)
String value = prop.getProperty(key);
System.out.println(key+"==" +value);
}
}
}
將集合中內容儲存到檔案
需求:使用Properties集合,完成把集合內容儲存到IO流所對應檔案中的操作
分析:
1,建立Properties集合
2,添加元素到集合
3,建立流
4,把集合中的資料存放區到流所對應的檔案中
stroe(Writer,comments)
store(OutputStream,commonts)
把集合中的資料,儲存到指定的流所對應的檔案中,參數commonts代表對描述資訊(uncoide編碼)
5,關閉流
代碼示範:
public class PropertiesDemo02 {
public static void main(String[] args) throws IOException {
//1,建立Properties集合
Properties prop = new Properties();
//2,添加元素到集合
prop.setProperty("周迅", "張學友");
prop.setProperty("李小璐", "賈乃亮");
prop.setProperty("楊冪", "劉愷威");
//3,建立流
FileWriter out = new FileWriter("prop.properties");
//4,把集合中的資料存放區到流所對應的檔案中
prop.store(out, "save data");
//5,關閉流
out.close();
}
}
讀取檔案中的資料,並儲存到集合
需求:從屬性集檔案prop.properties 中取出資料,儲存到集合中
分析:
1,建立集合
2,建立流對象
3,把流所對應檔案中的資料 讀取到集合中
load(InputStream) 把指定流所對應的檔案中的資料,讀取出來,儲存到Propertie集合中
load(Reader)
4,關閉流
5,顯示集合中的資料
代碼示範:
public class PropertiesDemo03 {
public static void main(String[] args) throws IOException {
//1,建立集合
Properties prop = new Properties();
//2,建立流對象
FileInputStream in = new FileInputStream("prop.properties");
//FileReader in = new FileReader("prop.properties");
//3,把流所對應檔案中的資料 讀取到集合中
prop.load(in);
//4,關閉流
in.close();
//5,顯示集合中的資料
System.out.println(prop);
}
}
注意:使用字元流FileReader就可以完成檔案中的中文讀取操作了
java ->properties類