——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-
生活中我们用的软件不完全是免费的,如果我们想给自己的程序加上试用限制该怎么做?
假如我现在有一个叫做"彩票预测器"的程序在测试类中只能运行3次,超过3次提示用户试用结束。
思路:
1.使用File对象封装一个记录次数文本文件
2. 第一次运行,判断文件是否存在,如果不存在 文件中写 次数=1
3. 第一次以后,运行一次,读取文件,看看次数是不是3,如果是3,不运行,不是3,次数++ ,并运行程序
import java.io.*;
import java.util.*;
//定义类,操作记录配置文件,运行次数,没有到达次数,类中方法返回真
class RunCount{
public boolean getCount()throws Exception{
System.out.println("本程序试用期为:3次");
//File对象,封装记录次数文件
File file = new File("d:\\count.txt");
//判断文件是不是存在
if(!file.exists()){
//创建文件,写上count=1
FileWriter fw = new FileWriter(file);
System.out.println("欢迎使用本程序");
fw.write("count=1");
fw.close();
return true;
}
//文件已经存在
//输入流读取文件
FileReader fr = new FileReader(file);
//创建集合对象
Properties pro = new Properties();
pro.load(fr);
fr.close();
//获取值
String value = pro.getProperty("count");
int count = Integer.parseInt(value);
if(count>=3){
//程序结束
System.out.println("使用次数已达上限");
return false;
}else{
count++;
pro.setProperty("count", count+"");
FileWriter fw = new FileWriter(file);
pro.store(fw, "");
fw.close();
System.out.println("已使用"+count+"次");
return true;
}
}
}
public class Test {
public static void main(String[] args) throws Exception{
RunCount r = new RunCount();
if(r.getCount()){
//运行程序
System.out.println("彩票预测器");
}else{
System.out.println("试用结束");
}
}
}
运行第一次的时候,在D盘下没有count.txt这个文件,
这时创建一个count.txt并写入count=1
之后每次运行的时候会读取count.txt获取用户使用的次数
到这一步的时候,count.txt中记录的次数为3,已达判断条件
所以再次运行程序肯定是不行啦!
于是,我的”彩票预测器”就成了有偿程序,试用3次就能用啦。
实际操作中可以把count的文件名弄古怪一些,路径整的深一些。