黑马程序员—Properties—限制与记录程序运行次数

来源:互联网 发布:pubmed数据库电脑官网 编辑:程序博客网 时间:2024/05/22 17:50

import java.io.*;
import java.util.*;
class JavaDemo04
{
 public static void main(String[] args)throws IOException
 {
  Properties prop=new Properties();//定义一个集合
  File file=new File("count.ini");//将count.ini封装成File对象
  if(!file.exists())//判断文件是否已经存在,如果不存在
   file.createNewFile();//创建文件
  FileInputStream fis=new FileInputStream(file);//定义一个输入流
  prop.load(fis);//把流中的数据加载到prop集合中

  int count=0;//定义一个计数器,初始值为0
  String value=prop.getProperty("time");//设置key为time,通过getProperty()获取该key的value
  if(value!=null)
  {
   count=Integer.parseInt(value);//将返回的value包装成Integer对象返回给count
   
   System.out.println("你的次数已到"+count+"次");
   count++;
   if(count>=5)
   {
    System.out.println("不好意思,你的次数已到5次");//限制为5次
    return;
   }
  }
  prop.setProperty("time",count+"");//将key和value存入Properties集合中
  FileOutputStream fos=new FileOutputStream(file);//定义一个输出流,将内容写入到file对象中
  prop.store(fos,"");//把流数据返回给Properties
  
  fis.close();
  fos.close();
  
 }
 
}

0 0
原创粉丝点击