用properties记录次数

/*
获取java程序运行的次数。
思路:
通过一个配置文件将运行次数进行记录。
每一次打开该程序时,都先加载这个文件获取其中的次数。
并对该次数自增,重新存回配置文件。

注意:次数可以直接用一个数值,但是如果,除了记录次数还要记录其他信息的时候,那么这些数值无法进行区分。
所以给这些数值都起了名字,出现了键值对。

步骤:
	1,通过流关联配置文件,可是配置文件第一次不存在,所以最好将配置文件封装成File对象,并进行判断。
	2,通过和流相结合的结合对象Properties的load方法,将流关联的数据存入到集合中。
	3,通过集合的方法获取指定键所以对应的次数,并将该次数进行自增。
	4,将集合中修改后的数据通过集合的store方法重新存入配置文件中。

*/

import java.util.*;
import java.io.*;
class  RunCount
{
	public static void main(String[] args) throws IOException
	{
		/**/
		Properties prop = new Properties();
		

		int count = 0;
		File file = new File("runcount.ini");

		if(!file.exists())
			file.createNewFile();

		FileInputStream fis = new FileInputStream(file);

		prop.load(fis);

		String value = prop.getProperty("count");

		if(value!=null)
		{
			count = Integer.parseInt(value);
			if(count==10)
			{
				System.out.println("次数已到,必须给钱,否则.....");
				return ;
			}
		}

		count++;

		prop.setProperty("count",Integer.toString(count));

		FileOutputStream fos = new FileOutputStream(file);

		prop.store(fos,"");
		
		fos.close();
		fis.close();
		
//		show();

	}

	public static void show()throws IOException
	{
		Properties prop = new Properties();
		

		int count = 0;
		File file = new File("runcount.ini");
		FileInputStream fis = null;
		
		try
		{
			fis = new FileInputStream(file);
			prop.load(fis);
		}
		catch (FileNotFoundException e)
		{
			prop.setProperty("count",count+"");
		}
		

		

		String value = prop.getProperty("count");

		if(value!=null)
		{
			count = Integer.parseInt(value);
			if(count==3)
			{
				System.out.println("次数已到,必须给钱,否则.....");
				return ;
			}
		}

		count++;

		prop.setProperty("count",Integer.toString(count));

		FileOutputStream fos = new FileOutputStream(file);

		prop.store(fos,"");
		
		fos.close();
		if(fis!=null)
			fis.close();
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值