每运行一次程序,使用次数就加一,到指定次数后提示使用次数已到。
第一步,生成一个.ini的配置文件,里面用键值对的形式存放数据。
File file = new File("info.ini");
if(!file.exists()) {
file.createNewFile();
}
第二步,需要用到使IO和Map相结合的类,util包中的Properties类。
Properties prop = new Properties();
第三步,建立输入流,与配置文件相关联。使用Properties类中的load方法读取输入流文件中的数据到prop中。
FileInputStream fis = new FileInputStream(file);
prop.load(fis);
第四步,获取对应键的值,用计数器累加之后再设置回去。
int count = 0; //计数器
String value = prop.getProperty("time");//根据键获取值
if(value!=null) {
count = Integer.parseInt(value); //字符串转int型
if(count>=5) {
System.out.println("使用次数已到,请购买!");
return;
}
}
count++;
prop.setProperty("time", count+"");//设置键值
第五步,建立输出流与配置文件相关联,使用Properties类中的store方法吧集合中的数据输出到与流关联的文件中。
FileOutputStream fos = new FileOutputStream(file);
prop.store(fos, "这里是注释信息,在配置文件当中不会被读取。");
最后一步,关闭输入输出流。
fis.close();
fos.close();