用于记录应用程序运行次数,如果使用次数已到那么就要给出注册提示;

时间:2022-01-05 22:32:22





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


/*
 * 用于记录应用程序运行次数,如果使用次数已到那么就要给出注册提示;
 * 第一想到的是计数器。
 * 可是该计数器定义在程序中,随着程序的运行而在内存中存在,并运行自增。
 * 可是随着该应用程序的退出,该计数器也就在内存中消失了,下一次在启动该程序又重新开始从零计数
 * 这样就不是我们想要的。
 * 程序即使结束,该计数器的值也存在,下次程序启动就会先加载该计数器的值并加一后在重新存储起来。
 * 所以要建立一个配置文件。用于记录该软件的使用次数。
 * 该配置文件使用键值对的形式,这样便于阅读数据,并操作数据。
 * 键值对数据是map集合,数据是以文件形式存储,使用io技术,那么map+io》》properties
 * 配置文件可以实现应用程序数据的共享。
 * 
 */
public class RunCount {
public static void main(String[] args) throws IOException {
Properties prop=new Properties();
File file=new File("count.properties");
if (!file.exists()) {
file.createNewFile();//判断文件是否存在,如果不存在则创建一个新的文件
}
FileInputStream fis=new FileInputStream("count.properties");
prop.load(fis);
int count=0;
String value=prop.getProperty("time");
if (value!=null) {

count=Integer.parseInt(value);//获取次数
if (count>=5) {
System.out.println("你好,使用次数已到,拿钱!");
return;
}
}
count++;
prop.setProperty("time", count+"");//获得次数
FileOutputStream fos=new FileOutputStream(file);//字节输出流
prop.store(fos, "");//调取文件
fos.close();
fis.close();














}




}