java-27 Properties类的使用

1.Properties 

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

2.方法

  setProperty(String key,String value)  调用 Hashtable 的方法 put

  getProperty()  用指定的键在此属性列表中搜索属性。

  load() 从输入流中读取属性列表(键和元素对)。

  PropertyNames() 返回属性列表中所有键的枚举,如果在主属性列表中未找到同名的键,则包括默认属性列表中不同的键。

  stringPropertyNames() 返回此属性列表中的键集,其中该键及其对应值是字符串,如果在主属性列表中未找到同名的键,则还包括默认属性列表中不同的键。

  store() 将键值对存入文件

public class Demo {
	public static void main(String[] args) throws Exception{
          //创建对象 Properties pro = new Properties();
          //添加数据 pro.setProperty("1", "zhangsan"); pro.setProperty("2", "lisi"); pro.setProperty("3", "wangwu");
          //得到键为“2”的值 String str = pro.getProperty("2"); System.out.println(str);
          //得到由键组成的set集合 Set<String> set = pro.stringPropertyNames();
          //遍历 for(String key:set) { System.out.println(key+":"+pro.getProperty(key)); } } }

 load方法

public class Demo {
	public static void main(String[] args) throws Exception{
		Properties pro = new Properties();
		FileReader f = new FileReader("d:\pro.properties");
		System.out.println(pro);
		pro.load(f);
		f.close();
		System.out.println(pro);
	}
}

 store() 方法

public class Demo {
	public static void main(String[] args) throws Exception{
		Properties pro = new Properties();
		FileWriter file = new FileWriter("d:\p.properties");
		pro.setProperty("1", "zhangsan");
		pro.setProperty("2", "lisi");
		pro.setProperty("3", "wangwu");
		pro.store(file, "");
		file.close();
	}
}

原文地址:https://www.cnblogs.com/smxbo/p/10718256.html