【需求】:
记录程序运行的次数,当程序的运行次数达到上限(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();
}
}
【截图】:

博客提出记录程序运行次数,达到上限(5次)禁止登陆的需求。因程序内计数器随程序结束重置,故采用文件存储运行次数,下次运行时从文件取出上次次数加1后再存储。
1293

被折叠的 条评论
为什么被折叠?



