JavaSE|Properties

public class Properties
extends Hashtable<Object,Object>
Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。

Properties作为Map集合的使用

Properties是Hashtable的子类,说明是一个Map集合。
其作为Map集合的使用如下:

		Properties prop = new Properties();
		
		prop.put("it002", "hello");
		prop.put("it001", "world");
		prop.put("itoo3", "java");
		
		Set<Object> set = prop.keySet();
		for(Object key : set){
			Object value = prop.get(key);
			System.out.println(key + "---" + value);
		}

构造方法:

  1. Properties()
    创建一个无默认值的空属性列表。
  2. Properties(Properties defaults)
    创建一个带有指定默认值的空属性列表。

注意:Properties不是泛型类,使用时不能加泛型。

Properties的特殊功能

  1. public Object setProperty(String key,String value)
  2. public String getProperty(String key)
  3. public Set< String > stringPropertyNames()
public class PropertiesDemo2 {
	public static void main(String[] args) {
		// 创建集合对象
		Properties prop = new Properties();

		// 添加元素
		prop.setProperty("张三", "30");
		prop.setProperty("李四", "40");
		prop.setProperty("王五", "50");

		// public Set<String> stringPropertyNames():获取所有的键的集合
		Set<String> set = prop.stringPropertyNames();
		for (String key : set) {
			String value = prop.getProperty(key);
			prop.setProperty("张三", "30");
		}
	}
}

/*
 * class Hashtalbe<K,V> { public V put(K key,V value) { ... } }
 * 
 * class Properties extends Hashtable { public V setProperty(String key,String
 * value) { return put(key,value); } }
 */

Properties和IO流的结合使用

  • 把键值对形式的文本文件内容加载到集合中
    void load(InputStream inStream)
    void load(Reader reader)

  • 把集合中的数据存储到文本文件中
    void store(OutputStream out, String comments)
    void store(Writer writer, String comments)

public class PropertiesDemo3 {

	public static void main(String[] args) throws IOException {

		//myLoad();
		myStore();
	}

	private static void myStore() throws IOException {
		Properties prop = new Properties();
		
		prop.setProperty("林青霞", "27");
		prop.setProperty("武鑫", "57");
		prop.setProperty("刘晓曲", "18");
		
		Writer w = new FileWriter("name.txt");
		prop.store(w, "helloworld");
		
		w.close();	
	}

	private static void myLoad() throws IOException {

		Properties prop = new Properties();
		
		// public void load(Reader reader):把文件中的数据读取到集合中
		// 注意:这个文件的数据必须是键值对形式
		Reader r = new FileReader("prop.txt");
		prop.load(r);
		r.close();
		
		System.out.println("prop:" + prop);		
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值