Properties的使用

来源:互联网 发布:艾默生网络能源被收购 编辑:程序博客网 时间:2024/06/07 05:15
/*Properties 类表示了一个持久的属性集,是hashtable的子类也就是说它具备Map集合的特点为,而且它里面存储的键值对都是字符串是集合中和io技术相合的集合容器该对象的特点,可以用键值对形式的配置文件那么在加载数据时,需要数据固定格式:键=值。*/import java.util.*;import java.io.*;class  PropertiesDemo{public static void main(String[] args) throws IOException{//setAndGet();//fileToProperty(); loadProperty();}//演示Properties 加载流中的数据 和 把流中的数据存储到文件中public static void loadProperty()throws IOException{Properties prop = new Properties();FileInputStream fis = new FileInputStream("info.ini");//将流中的数据加载进集合prop.load(fis); //改变内存中的结果。prop.setProperty("ah","09");//fis.close();FileOutputStream fout = new FileOutputStream("info.ini");prop.store(fout,"注释信息");fis.close();fout.close();System.out.println(prop);}//演示,如何将流中的数据存储到集合中//想要将info.ini 中键值数据存储到集合中进行操作/*思路:1:用一个流和info.ini文件关联2:读取一行数据,将该行数据用“="进行分割3:等号左边作为键,右边作为值。存入到Properties集合中。*/public static void fileToProperty()throws IOException{BufferedReader br = new BufferedReader(new FileReader("info.ini"));String line = null;Properties prop = new Properties();while((line = br.readLine())!=null){String[] arr = line.split("=");//分割System.out.println(arr[0]+"..."+arr[1]);prop.setProperty(arr[0],arr[1]);}br.close();}//设置和获取元素public static void setAndGet(){Properties prop = new Properties();prop.setProperty("zhangsan","20");prop.setProperty("lisi","30");//System.out.println(prop);String value = prop.getProperty("lisi");System.out.println(value);//返回此属性列表中的键集,其中该键及其对应值是字符串Set<String> setProp = prop.stringPropertyNames();for(String temp : setProp){System.out.println(temp+": "+prop.getProperty(temp));}}}

0 0