Java之Property-统获取一个应用程序运行的次数

 1 package FileDemo;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.util.Properties;
 8 
 9 public class PropertyTest {
10 
11     /**
12      * @param args
13      * @throws IOException 
14      */
15     public static void main(String[] args) throws IOException {
16 
17 
18         /*
19          * 定义功能,获取一个应用程序运行的次数,如果超过5次,给出使用次数已到请注册的提示。并不要在运行程序。
20          * 
21          * 思路: 1,应该有计数器。 每次程序启动都需要计数一次,并且是在原有的次数上进行计数。 2,计数器就是一个变量。
22          * 突然冒出一想法,程序启动时候进行计数,计数器必须存在于内存并进行运算。
23          * 可是程序一结束,计数器消失了。那么再次启动该程序,计数器又重新被初始化了。 而我们需要多次启动同一个应用程序,使用的是同一个计数器。
24          * 这就需要计数器的生命周期变长,从内存存储到硬盘文件中。
25          * 
26          * 3,如何使用这个计数器呢? 首先,程序启动时,应该先读取这个用于记录计数器信息的配置文件。 获取上一次计数器次数。 并进行使用次数的判断。
27          * 其次,对该次数进行自增,并自增后的次数重新存储到配置文件中。
28          * 
29          * 
30          * 4,文件中的信息该如何进行存储并体现。 直接存储次数值可以,但是不明确该数据的含义。 所以起名字就变得很重要。
31          * 这就有了名字和值的对应,所以可以使用键值对。 可是映射关系map集合搞定,又需要读取硬盘上的数据,所以map+io =
32          * Properties.
33          */
34         getAppCount();
35     }
36 
37     private static void getAppCount() throws IOException {
38         File conFile = new File("count.properties");
39         if (!conFile.exists()) {
40             conFile.createNewFile();
41         }
42         FileInputStream fis = new FileInputStream(conFile);
43         Properties prop = new Properties();
44         prop.load(fis);
45         String values = prop.getProperty("time");
46         int count = 0;
47         if (values != null) {
48             count = Integer.parseInt(values);
49             if (count > 5) {
50                 throw new RuntimeException("使用次数限制已到");
51             }
52         }
53         count++;
54         prop.setProperty("time", count+"");
55         FileOutputStream fos = new FileOutputStream(conFile);
56         prop.store(fos, "");
57         fos.close();
58         fis.close();
59 
60     }
61 }
原文地址:https://www.cnblogs.com/ysw-go/p/5300933.html