---
title: "计数器应用例子"
author: "mywebcode"
date: "2013-10-27T20:37:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2014-04-30T09:09:14Z"
id: 2057860
url: "https://mywebcode.iteye.com/blog/2057860"
---

\*需求：获取一个应用程序的运行次数，如果超过5次，给出使用次数已到，请注册的提示。并不要再运行该程序。  
\*  
\*思路：  
\* 1、应该有计数器  
\* 每次程序启动都要计数一次，并且是在原有的次数上进行计数  
\* 2、计数器就是一个变量，程序启动后进行计数，计数器必须存在于内存，并进行运算  
\* 可是程序一结束，计数器就消失，那么程序再次启动时，计数器又重新被初始化。  
\*  
\* 3、如何使用计数器，计数

\* 程序启动时，应该先读取这个用于记录计数信息的配置文件

```
package com.xuan.chan;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

import com.sun.org.apache.commons.collections.StaticBucketMap;



/**
 * @author Administrator
 */
public class PropertiesTest {
    
	public static void main(String[] args) throws IOException{
		
		countTest();
	}

	
	//计数，试用期只有五天
	private static void countTest() throws IOException, FileNotFoundException {
		File file=new File("haha.properties");
		if(!file.exists()){
			file.createNewFile();
		}
		
		FileInputStream fis=new FileInputStream(file);
		Properties properties=new Properties();
		///把流中的数据加载到集合智中
		properties.load(fis);
		String value=properties.getProperty("time");
		
		int count=0;
		if(value!=null){
			count=Integer.parseInt(value);
			if(count>=5){
				//System.out.println("使用超过5次");
				//return;
				throw new RuntimeException("使用次数已到，请注册，试用期已到，请注册");
			}
		}
		
		count++;
		
		properties.setProperty("time", count+"");
		FileOutputStream fos=new FileOutputStream(file);
		///将改变后的数据重新保存到文件中
		properties.store(fos, "count");

		fos.close();
		fis.close();
	}
	
	
}
```