编写程序实现记录程序的运行次数。
代码如下:
import java.io.*;
import java.util.*;
public class PropertiesFile {
public static void main(String[] args) {
Properties settings = new Properties();
try {
settings.load(new FileInputStream("count.txt"));
} catch (Exception e) {
settings.setProperty("count", String.valueOf(0));
}
int c = Integer.parseInt(settings.getProperty("count")) + 1;
System.out.println("这是第" + c + "次运行");
// settings.put("count", new Integer(c).toString());
settings.setProperty("count", new Integer(c).toString());
try {
settings.store(new FileOutputStream("count.txt"),
"program is used:");
} catch (Exception e) {
e.getStackTrace();
}
}
}
运行结果:
在硬盘里自动生成的count.txt文件里的内容:
本例首先使用Properties类里大load函数来加载count.txt文件中的count关键字,因为第一次没有count.txt文件,所以会出现异常,在catch语句里设count初始值为0,之后加1打印出来。再使用store方法将count的数值存到count.txt文件中,如果没有此文件就创建一个(第一次就是)。