/*
获取java程序运行的次数。
思路:
通过一个配置文件将运行次数进行记录。
每一次打开该程序时,都先加载这个文件获取其中的次数。
并对该次数自增,重新存回配置文件。
注意:次数可以直接用一个数值,但是如果,除了记录次数还要记录其他信息的时候,那么这些数值无法进行区分。
所以给这些数值都起了名字,出现了键值对。
步骤:
1,通过流关联配置文件,可是配置文件第一次不存在,所以最好将配置文件封装成File对象,并进行判断。
2,通过和流相结合的结合对象Properties的load方法,将流关联的数据存入到集合中。
3,通过集合的方法获取指定键所以对应的次数,并将该次数进行自增。
4,将集合中修改后的数据通过集合的store方法重新存入配置文件中。
*/
import java.util.*;
import java.io.*;
class RunCount
{
public static void main(String[] args) throws IOException
{
/**/
Properties prop = new Properties();
int count = 0;
File file = new File("runcount.ini");
if(!file.exists())
file.createNewFile();
FileInputStream fis = new FileInputStream(file);
prop.load(fis);
String value = prop.getProperty("count");
if(value!=null)
{
count = Integer.parseInt(value);
if(count==10)
{
System.out.println("次数已到,必须给钱,否则.....");
return ;
}
}
count++;
prop.setProperty("count",Integer.toString(count));
FileOutputStream fos = new FileOutputStream(file);
prop.store(fos,"");
fos.close();
fis.close();
// show();
}
public static void show()throws IOException
{
Properties prop = new Properties();
int count = 0;
File file = new File("runcount.ini");
FileInputStream fis = null;
try
{
fis = new FileInputStream(file);
prop.load(fis);
}
catch (FileNotFoundException e)
{
prop.setProperty("count",count+"");
}
String value = prop.getProperty("count");
if(value!=null)
{
count = Integer.parseInt(value);
if(count==3)
{
System.out.println("次数已到,必须给钱,否则.....");
return ;
}
}
count++;
prop.setProperty("count",Integer.toString(count));
FileOutputStream fos = new FileOutputStream(file);
prop.store(fos,"");
fos.close();
if(fis!=null)
fis.close();
}
}