------- android培训、java培训、期待与您交流! ----------
十、Properties类
Properties是hashtable的子类。
也就是说它具备map集合的特点。而且它里面存储的键值都是字符串。
是集合中和IO技术相结合的集合容器。
该对象的特点:可以用于键值对形式的配置文件。
10.1、Properties存取
getProperty(String key) 用指定的键在此属性列表中搜索属性。
getProperty(String key, String defaultValue) 用指定的键在属性列表中搜索属性。
示例如下:
class Properties
{
public static void main(String[] args)
{
setAndGet()
}
//设置和获取元素
public static void setAanGet()
{
Propertise prop = new Propertise();
prop.setProperty("zhangsan","23");
prop.setProperty("lisi","53");
String value = prop.getProperty("lisi");
prop.setProperty("lisi","13");
Set<String> names = prop.stringPropertyNames();
for(String s: name)
{
System.out.print(s + ":" + prop.getProperty(s));
}
}
}
10.2、Properties存取配置文件
如何将流中的数据存储到集合中。
1、用一个流和文件关联。
2、读取一行数据,将文件数据用“=”进行切割。
3、等号左边为键,右边为值。存入到Properties集合中即可。
使用示例1:
class Properties
{
public static void main(String[] args) throws IOException
{
method()
}
//存储流中的数据到集合中
public static void method() throws IOException
{
BufferedReader bufr = new BufferedReader (new FileReader("info.txt"));
String line = null;
Properties prop = new Properties();
while((line = bufr.readLine())!=null)
{
String[] arr = line.split("=");
prop.setProperty(arr[0],arr[1]);
}
bufr.close();
System.out.print(prop);
}
}
使用示例2:
class Properties
{
public static void main(String[] args) throws IOException
{
loadDemo()
}
//存储流中的数据到集合中
public static void loadDemo() throws IOException
{
Properties prop = new Properties();
FileInputStream fis = new FileInputStream ("info.txt");
//将流中的数据加载进集合
prop.load(fis);
prop.setProperty("mazi","51");
FileOutputStream fos = new FileOutputStream ("info.txt");
prop.store(fos,"haha");
prop.list(System.out);
fos.close();
fis.colse();
}
}
java1.6以上才使用的方法。
总结:在加载数据时,需要数据有固定格式:键=值。