黑马程序员技术交流社区

标题: Properties 创建一个配置文件 限制程序运行次数 [打印本页]

作者: fmi110    时间: 2015-8-8 09:37
标题: Properties 创建一个配置文件 限制程序运行次数
Properties
  1. /*
  2. 需求:创建一个配置文件,当程序运行到达5次时,不允许再运行
  3. 分析:        1、配置文件需要长期保存在硬盘,所以需要文件流
  4.                 2、需要读取文件使用次数,所以考虑使用集合
  5.                 3、集合和IO流结合,所以使用Properties
  6. */
  7. import java.io.*;
  8. import java.util.*;
  9. class PropertiesTest
  10. {
  11.         public static void main(String[] args) throws IOException
  12.         {
  13.                 //创建抽象文件目录,并判断配置文件是否已存在,若不存在则新建一个,
  14.                 //已存在则读取存入Properties
  15.                 File file = new File("count.ini");
  16.                 //判断
  17.                 if(!file.exists())
  18.                         file.createNewFile();
  19.                 //创建流,读取配置文件
  20.                 FileInputStream fin = new FileInputStream(file);
  21.                 //将配置信息 存至集合Properties
  22.                 Properties prop = new Properties();
  23.                 //加载信息
  24.                 prop.load(fin);

  25.                 int count = 0 ;
  26.                 String value = prop.getProperty("time");
  27.                 if(value!=null){
  28.                         count = Integer.parseInt(value);
  29.                         if(count>=5)
  30.                         {
  31.                                 System.out.println("该交钱啦啦啦啦啦");
  32.                                 return ;
  33.                         }
  34.                 }
  35.                 count++;
  36.                 prop.setProperty("time",String.valueOf(count));
  37.                 FileOutputStream fos = new FileOutputStream(file);
  38.                 prop.store(fos,"");
  39.                 fos.close();
  40.                 fin.close();

  41.                 System.out.println("Hello World!");
  42.         }
  43. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2