Properties是hashtable的子类
也就是说它具备map集合的特点。而且它里面存储的键值对都是字符串
是集合中和IO技术相结合的集合容器
该对象的特点:可以用于键值对形式的配置文件
那么在加载数据时, 需要数据有固定格式:键=值
代码:
import java.io.*;
import java.util.*;
class PropertiesDemo
{
public static void main(String[] args)throws IOException
{
//setAndGet();
//method_1();
loadDemo();
}
public static void loadDemo()throws IOException
{
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("info.txt");
prop.load(fis);//将流中的数据加载到集合
prop.setProperty("wangwu", "39");//改变内存中的结果,并没有存到文件中
FileOutputStream fos = new FileOutputStream("info.txt");
prop.store(fos,"haha");//把修改后的信息存储到文件中,"haha"为备注信息存储到info.txt
//System.out.println(prop);
prop.list(System.out);//列出集合目录,相当于输出语句
fos.close();
fis.close();
}
//演示,如何将流中的数据存储到集合中
//想要将info.txt中的键值数据存到集合中进行操作
/*
1,用一个流和info.txt文件关联
2,读取一行数据,将该行数据用“=”进行切割
3,等号左边作为键,右边作为值。存入到Properties集合
*/
public static void method_1()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("=");
//System.out.println(arr[0]+"..."+arr[1]);
prop.setProperty(arr[0], arr[1]);
}
bufr.close();
System.out.println(prop);
}
//设置和获取元素
public static void setAndGet()
{
Properties prop = new Properties();//创建Properties集合对象
prop.setProperty("zhangsan", "30");//设置键值
prop.setProperty("lisi", "39");
//System.out.println(prop);//输出prop对象的键值
String value = prop.getProperty("lisi");//获取键对应的值
System.out.println(value);
prop.setProperty("lisi", 89+"");//重置lisi
Set<String> names = prop.stringPropertyNames();//创建键对象
for(String s : names)
{
System.out.println(s+"....."+prop.getProperty(s));
}
}
}
------------------------------------------------------------------------------------------------
用于记录应用程序运行次数
如果使用次数已到,那么给出注册提示
很容易想到:计数器
可是该计数器定义在程序中,随着程序的运行而在内存中存在,
并进行自增。
可是随着该应用程序的退出,该计数器也在内存中消失。
下一次再启动该程序,又重新开始从0计数。
程序即使结束,该计数器的值也存在。
下次程序启动会先加载该计数器的值并加1后再重新存储起来
所以要建立一个配置文件,用于记录该软件的使用次数。
该配置文件使用键值对的形式。
这样便于阅读数据,并操作数据。
键值对数据是map集合。
数据是以文件形式存储,使用io技术。
那么map+io ----> properties
配置文件可以实现应用程序数据的共享
代码:
import java.io.*;
import java.util.*;
class RunCount
{
public static void main(String[] args)throws IOException
{
Properties prop = new Properties();//创建集合对象
File file = new File("count.ini");//创建文件对象
if(!file.exists())//判断文件是否存在,没有就建一个
file.createNewFile();
FileInputStream fis = new FileInputStream(file);
prop.load(fis);//流中数据加载到集合
int count = 0;
String value = prop.getProperty("time");//通过键拿值
if(value != null)
{
count = Integer.parseInt(value);//把字符串转成整形数据
if(count>=5)
{
System.out.println("您好,使用次数已到");
return ;
}
}
count++;
prop.setProperty("time", count+"");必须写成count+"",表示数字转成字符串
FileOutputStream fos = new FileOutputStream(file);
prop.store(fos,"");//存储到文件中
fos.close();
fis.close();
}
}
------------------------------------------------------------------------------------------------------
个人总结: Properties是util包中的类,掌握Properties中的方法使用,这是一个和集合相关的,
里面存储键值对,且以字符串形式存在,有固定的书写格式,注意load和store方法的使用