java编写程序,程序运行时输出上次运行的开始时间和结束时间,然后用户按任意键退出程序。用property 方法来编写
时间: 2023-12-10 07:41:51 浏览: 36
下面是使用 Property 方法编写的 Java 程序,可以输出上次运行的开始时间和结束时间,并等待用户按任意键退出程序:
```java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;
public class LastRunTime {
public static void main(String[] args) throws IOException, InterruptedException {
Properties props = new Properties();
FileInputStream in = new FileInputStream("lastruntime.properties");
props.load(in);
in.close();
String startTime = props.getProperty("start_time");
String endTime = props.getProperty("end_time");
if (startTime != null && endTime != null) {
System.out.println("上次运行时间:" + startTime + " - " + endTime);
}
String newStartTime = getCurrentTime();
System.out.println("本次运行开始时间:" + newStartTime);
Scanner scanner = new Scanner(System.in);
System.out.println("按任意键退出程序。");
scanner.nextLine();
String newEndTime = getCurrentTime();
System.out.println("本次运行结束时间:" + newEndTime);
props.setProperty("start_time", newStartTime);
props.setProperty("end_time", newEndTime);
FileOutputStream out = new FileOutputStream("lastruntime.properties");
props.store(out, "Last run time");
out.close();
}
private static String getCurrentTime() {
return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
}
}
```
该程序使用 Properties 类来读取和写入一个名为 lastruntime.properties 的文件,该文件保存了上次运行的开始时间和结束时间。当程序运行时,它会首先从该文件中读取上次运行的时间,如果存在则输出。然后程序会输出本次运行的开始时间,并等待用户按任意键退出程序。当用户按下任意键后,程序会输出本次运行的结束时间,并把本次运行的开始时间和结束时间保存到 lastruntime.properties 文件中。