java编写程序,程序运行时输出上次运行的开始时间和结束时间,然后用户按任意键退出程序。用property 方法来编写
时间: 2023-12-03 12:44:24 浏览: 36
可以使用 `java.util.Properties` 类来保存上次运行的开始时间和结束时间,具体实现如下:
```java
import java.util.Date;
import java.util.Properties;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Program {
public static void main(String[] args) {
Properties props = new Properties();
InputStream in = null;
OutputStream out = null;
try {
// 读取配置文件
in = new FileInputStream("config.properties");
props.load(in);
// 获取上次运行的开始时间和结束时间
String startTimeStr = props.getProperty("start_time");
String endTimeStr = props.getProperty("end_time");
// 输出上次运行的时间
if (startTimeStr != null && endTimeStr != null) {
Date startTime = new Date(Long.parseLong(startTimeStr));
Date endTime = new Date(Long.parseLong(endTimeStr));
System.out.println("上次运行的开始时间:" + startTime);
System.out.println("上次运行的结束时间:" + endTime);
}
// 记录本次运行的时间
Date startTime = new Date();
// 程序的主要逻辑
// ...
Date endTime = new Date();
// 保存本次运行的时间
props.setProperty("start_time", String.valueOf(startTime.getTime()));
props.setProperty("end_time", String.valueOf(endTime.getTime()));
out = new FileOutputStream("config.properties");
props.store(out, "Last run time");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
// 等待用户按任意键退出程序
System.out.print("按任意键退出程序...");
try {
System.in.read();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
```
上面的程序通过 `Properties` 类保存上次运行的开始时间和结束时间,然后在本次运行时读取这些属性值并输出,最后保存本次运行的时间。程序结束时等待用户按任意键退出。注意,需要在程序运行目录下创建名为 `config.properties` 的配置文件。