/*
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));
}
}
}
Properties的使用
最新推荐文章于 2024-07-14 09:22:16 发布