黑马程序员-Properties

 

----------- android培训java培训java学习型技术博客、期待与您交流! ------------ 

 

 

Properties 简述

 

Properties是hashtable的子类
也就是说它具备了map集合的特点,而且它里面存储的键值对都是字符串

是集合中和IO技术相结合的集合容器

该对象的特点:可以用键值对形式的配置文件

 

不仅可以操作键值对,还可以操作硬盘上的键值对~
void list(PrintWriter out);
void list(PrintStream out);
将属性列表输出到指定输出流

 

void load(InputStream inStream);
从输入流中读取属性列表(键和元素对)
void load(Reader reader);
按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)

 

Properties 存取

 

static getProperty(String key,String value);
static setProperty(String key,String value);
Set<String> stringPropertyNames();
返回此属性列表中的键集,其中该键及其对应值是字符串,若主属性列表中未找到同名的键,则还包括默认属性列表中不同的键。

 

public static void main(String[] args)
{


 }

 


//设置和获取元素
public static void setAndGet()
{
 Properties prop = new Properties();


 prop.setProperty("zhangsan","30");
 prop.setProperty("lisi","23");

 //System.out.println(prop);

 

 String value = prop.getProperty("lisi");

 

 prop.stringPropertyNames();


 for(String s :names)
 {
  System.out.println(s+"::"+prop.getProperty(s));
 }


 prop.setProperty("lisi",89+"");
 //修改值


}


Properties 存取配置文件

想要将info.txt中的键值数据存到集合中进行操作?

1、用一个流和info.txt文件关联
2、读取一行数据,将该行数据用“=”进行切割。
3、等号左边作为键,右边作为值,存入到Properties集合中即可。

在加载数据时,需要有固定格式,通常是 键=值


public static void method_1()
{
 BufferedReader bufr = new BufferedReader(new FileReader("info.txt"));
 String line = null;
 while((line=bufr.readLine())!=null)
 {
  String[] arr = line.split("=");
  prop.setProperty(arr[0],arr[1]);
 }
 bufr.close();
}


所以Properties有load方法供使用

FileInputStream fis = new FileInputStream("info.txt");
Properties prop = new Properties();
加载字符流是1.6版本才有的
prop.load(fis);

也可以直接列出:list
prop.list(System.out);

修改:
prop.setProperty("wangwu","39");

void store(OutputStream out,String comments);
void store(Writer writer,String comments);


comments是注释信息

FileOutputStream fos = new FileOutputStream("info.txt");
prop.store(fos,"haha");

前面带#为注释信息,不会被Properties加载

 

Properties练习

用于记录应用程序运行次数,若使用次数已到,那么给出注册提示。

该配置文件使用键值对的形式便于阅读和操作
数据以文件形式存储, 使用IO技术
那么map+io--》properties
配置文件可以实现应用程序数据的共享

 

public static void main(String[] args)
{
 Properties prop = new Properties();
 操作文件养成习惯,先封装一个对象:
 File file = new File("count.ini");

 封装对象后可以进行判断等操作
 if(!file.exists())
  file.createNewFile();

 FIleInputStream ifs = new FileInputStream("count.ini");

 prop.load(fis);

 String value = prop.getProperty("time");
 if(value!=null)
  count = Integer.parseInt(value);

 if(count>=5)
 {
  ...
  return;
 }
 prop.setProperty("time",count+"");

 FileOUtputStream fos = new FileOUtputStream(fos);

 prop.store(fos,"");
 fos.close();
 fis.close();
}

 

<persons>
 <person id="001">
  <name>zhangsan</name>
  <age>30</age>
 </person>
</persons>


 

----------- android培训java培训java学习型技术博客、期待与您交流! ------------ 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值