Properties记录程序上次运行时间
时间: 2024-02-11 20:07:59 浏览: 34
可以使用Java中的Properties类来记录程序上次运行时间,具体步骤如下:
1. 在程序启动时,读取上次运行时间。可以使用如下代码实现:
```java
Properties props = new Properties();
FileInputStream in = new FileInputStream("config.properties");
props.load(in);
in.close();
String lastRunTime = props.getProperty("lastRunTime");
```
2. 在程序结束时,将本次运行时间保存到Properties文件中。可以使用如下代码实现:
```java
Properties props = new Properties();
FileOutputStream out = new FileOutputStream("config.properties");
props.setProperty("lastRunTime", new Date().toString());
props.store(out, "Last run time");
out.close();
```
3. 注意,在使用Properties保存数据时,需要在文件开头添加注释,以便更好地描述该文件的作用和内容。可以使用如下代码实现:
```java
Properties props = new Properties();
FileOutputStream out = new FileOutputStream("config.properties");
props.setProperty("lastRunTime", new Date().toString());
props.store(out, "Last run time");
// add comments to the properties file
out.write("# Configuration file\n".getBytes());
out.write("# Last run time of the program\n".getBytes());
out.close();
```
通过使用Properties类,可以方便地记录程序上次运行时间,并且该方法不需要额外的依赖库,非常方便。
相关推荐
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)