一、概述
1、properties的特点
1,Hashtable的子类,map集合中的方法都可以使用
2,该集合没有泛型,因为键值都是字符串
3,它是一个可以持久化的属性集,键值可以存储到集合中,也可以存储到持久化的设备上。
键值的来源也可以是持久化的设备
2,该集合没有泛型,因为键值都是字符串
3,它是一个可以持久化的属性集,键值可以存储到集合中,也可以存储到持久化的设备上。
键值的来源也可以是持久化的设备
2、特有方法
1,存数据
public Object setProperty(Stirng key,String value)参数 : key - 要置于属性列表中的键。value - 对应于 key 的值。
返回 : 属性列表中指定键的旧值,如果没有值,则为 null。
2,获取所有键
public Set<String> stringPropertyNames()返回 :属性集中的键集,其中该键及其对应值是字符串,包括默认属性列表中的键
3,根据键取值
public String getProperty(String key)参数 :key - 属性键。
返回 :key对应的值
4、Property持久化键值对
public void store(OutputStream out,String comments) throws IOException Properties 表中的属性列表(键和元素对)写入输出流。参数:out - 输出流。comments - 属性列表的描述。
<span style="white-space:pre"> </span>public static void stroeTest() throws IOException {
Properties prop = new Properties();
prop.setProperty("zhangsan","20");
prop.setProperty("lisi","15");
prop.setProperty("wangwu","25");
//将集合中的数据持久化到存储设备上
//首先创建输出流对象
FileOutputStream fos = new FileOutputStream("tempfile\\info.properties");
//使用properties的store方法
prop.store(fos,"person info")
fos.close();
}
5、 加载设备中的数据
public void load(InputStream inStream) throws IOException 从输入流中读取属性列表参数:输入流
二、Properties应用实例
需求:记录程序运行的次数,满足五次后,提示,试用结束
思路:
1,定义计数器。
2,计数器的生命周期要比应用程序的生命周期长,所以需要将计数器的值进行持久化。
count = 1,里面存储的应该是键值对,Map集合,要和设备上的数据相关联。需要IO技术
集合+IO = Properties
1,定义计数器。
2,计数器的生命周期要比应用程序的生命周期长,所以需要将计数器的值进行持久化。
count = 1,里面存储的应该是键值对,Map集合,要和设备上的数据相关联。需要IO技术
集合+IO = Properties
<span style="white-space:pre"> </span>public static boolean checkCount() {
boolean isRun = true;
int count = 0;
//1,将配置文件封装成File对象,因为要判断文件是否存在。
File configFile = new File("tempflie\\count.properties");
if(!configFile.exists()){ //如果不存在,就创建。
configFile.createNewFile();
}
properties prop = new properties();
//2,定义流对象
FileInputStream fis = new FileInputStream(configFile);
//3,将流中的数据加载到集合中
prop.load(fis);
//4,获取对应的次数
String value = prop.getProprety("count");
if(value!=null){
count = Integer.parseInt(value);
if(count>=5){
System.out.println("试用次数已到");
isRun = false;
}
}
count++; //对取出的次数进行自增。
//将键count 和自增后的值存储到集合中
prop.setProperty("count",Integer.toString(count));
//将集合中的数据存储到配置文件中
FileOutputStream fos = new FileOutputStream(configFile);
prop.store(fos,"")
fos.close();
fis.close()
return isRun()
}