对Properties类的应用

来源:互联网 发布:linux的系统架构 编辑:程序博客网 时间:2024/04/27 15:02

编写程序实现记录程序的运行次数。
代码如下:

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文件中,如果没有此文件就创建一个(第一次就是)。

1 0
原创粉丝点击