【需求】:
记录程序运行的次数,当程序的运行次数达到上限(5次)后,禁止登陆。
思路:
由于计数器存在于程序内,随着程序的结束而结束;在重新运行程序时,计数器置为0;
所以这里采用一个文件来存储运行次数,第二次运行时,从文件夹里拿出上次运行的次数,进行加1后存储。
【代码】:
import java.io.*;
import java.util.*;
class Count
{
public static void main(String[] args) throws IOException
{
Properties pro=new Properties();
File file=new File("d:\\WorkSpace\\IO流\\properties.txt");
if(!file.exists()){
file.createNewFile();
}
FileInputStream fis=new FileInputStream(file);
pro.load(fis);
String value=pro.getProperty("time");
int num=0;
if(value!=null){
num=Integer.parseInt(value);
if(num>=5){
System.out.println("试用次数已达上限,请充值后登陆");
return ;
}
}
num++;
pro.setProperty("time",num+"");
FileOutputStream fos=new FileOutputStream(file);
pro.store(fos,"");
fos.close();
fis.close();
}
}
【截图】: