Properties集合

来源:互联网 发布:jdk for mac 编辑:程序博客网 时间:2024/04/27 16:03

IO流+集合=properties

特点:1.properties是Hashtable的子类,因此map集合中的方法都可以调用;

2.该集合没有泛型,键值对都是字符串;

3.是一个可持久化的属性集。也就是说可以利用流对象,将其数据持久化,键值对的来源也可以使持久化的设备。

举例1,将集合中的数据保存到文件中,尝试修改文件中的数据,并且保存。

说明,其中methodDemo() 是将集合中的数据持久化到一个文件中,methodDemo2() 是将文件中的数值进行改变,然后保存。

import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties;public class PropertiesDemo {public static void main(String[] args) throws IOException {// TODO Auto-generated method stubmethodDemo2();}public static void methodDemo2() throws IOException{//读取流中的数据FileInputStream fis=new FileInputStream("Properties1.properties");Properties pro=new Properties();pro.load(fis);//修改数据pro.setProperty("lisi", "20");//重新修改的数据重新持久化FileOutputStream fos=new FileOutputStream("Properties1.properties");pro.store(fos, "");//关流fos.close();fis.close();}public static void methodDemo() throws IOException{Properties pro=new Properties();pro.setProperty("wangwu", "23");pro.setProperty("lisi", "24");//将数据保存到文件中(持久化)FileOutputStream  fos=new FileOutputStream("Properties1.properties");pro.store(fos, "my demo,person info");fos.close();/* * 读取数据Set<String> set=pro.stringPropertyNames();for(String str:set){String value=pro.getProperty(str);System.out.println(str+"....."+value);}*/}}

例2:
定义一个功能,记录程序运行的次数。满足5次后,给出提示,试用次数已到,请注册!

//例2import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.Properties;public class PropertiesDemo2 {public static void main(String[] args) throws IOException {// TODO Auto-generated method stub/* * 需求:定义一个功能,记录程序运行的次数。满足5次后,给出提示,试用次数已到,请注册! *  */boolean b=isRun();if(b){runmethod();}}private static boolean isRun() throws IOException {// TODO Auto-generated method stubboolean isrun=true;int count=0;//创建配置文件File configerFile=new File("Configer.properties");if(!configerFile.exists()){configerFile.createNewFile();}FileInputStream fis=new FileInputStream(configerFile);//创建集合,存储数据Properties pro=new Properties();pro.load(fis);String value=pro.getProperty("count");if(value!=null){ count = Integer.parseInt(value); if(count>=5){ System.out.println("运行次数已到,请注册!"); isrun=false; }}count++;pro.setProperty("count", Integer.toString(count));//将集合中的数据存储到配置文件FileOutputStream fos=new FileOutputStream(configerFile);pro.store(fos, "count");fos.close();fis.close();return isrun;}public static void runmethod(){System.out.println("软件运行");}}




0 0