package 计算程序运行次数;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;
public class Demo {
private static int count;
public static void main(String[] args) throws Exception, Exception {
while(true){//死循环,多次操作显示更加直观,不过需要强行终止 可以在 判断前再次添加判断条件,设置结束方法
System.out.println("是否需要初始化 y/s");
String str = (new Scanner(System.in)).next();
if(str.equals("y")){
writeFileFirst();
writeFile();
readFile();
}else{
writeFile();
readFile();}
}
}
public static void writeFile() throws FileNotFoundException, IOException{//写入文件计算次数
Properties p = new Properties();
p.load(new FileInputStream(new File("C:/Users/刘晖/Desktop/计数.txt")));
count = Integer.parseInt(p.getProperty("yxcs"));//计数器通过获取原有文件的键值获取上次程序运行的计数
count++;//本次程序计算加一
p.setProperty("yxcs", count + "");
p.store(new FileOutputStream(new File("C:/Users/刘晖/Desktop/计数.txt")), "Snum");
}
public static void readFile() throws FileNotFoundException, IOException{//读取文件获得次数
Properties p = new Properties();
p.load(new FileInputStream(new File("C:/Users/刘晖/Desktop/计数.txt")));
String str = p.getProperty("yxcs");
System.out.println("当前运行次数:"+str);
}
public static void writeFileFirst() throws FileNotFoundException, IOException{//初始化作用
Properties p = new Properties();
p.setProperty("yxcs", "0");
p.store(new FileOutputStream(new File("C:/Users/刘晖/Desktop/计数.txt")), "Snum");
}
}
利用Properties类通过IO流统计程序的运行次数
猜你喜欢
转载自blog.csdn.net/weixin_38170523/article/details/83757439
今日推荐
周排行